将输入占位符文本与span文本jquery交换

Swap input placeholder text with span text jquery

本文关键字:文本 jquery 交换 span 占位符 输入      更新时间:2023-09-26

我有问题,比如如何将输入占位符文本与span文本交换。。。

    <div class="form-inputs">
      <div class="control-group string required user_name error error_state">
        <label class="string required control-label" for="user_name"><abbr title=
          "required">*</abbr> Name</label>
          <div class="controls">
            <div class="input-prepend">
              <input class="string required" id="user_name" maxlength="100" name=
              "user[name]" pattern="^[^0-9`!@#'$%'^&amp;*+_=]+$" placeholder=
              "Full Name" size="50" type="text" value="" />
            </div>
            <span class="help-inline">can't be blank</span>
          </div>
      </div>
        <div class="control-group email required user_email error input-error">
          <label class="email required control-label" for="user_email"><abbr title=
            "required">*</abbr> Email</label>
            <div class="controls">
              <div class="input-prepend">
                <input class="string email required" id="user_email" maxlength="255"
                name="user[email]" pattern="'A[^@'s]+@([^@'s]+'.)+[^@'s]+'z" placeholder=
                "Email" size="50" type="text" value="" />
              </div>
              <span class="help-inline">can't be blank</span>
            </div>
        </div>
          <div class="control-group password required user_password error input-error">
            <label class="password required control-label" for=
            "user_password"><abbr title="required">*</abbr> Password</label>
            <div class="controls">
              <div class="input-prepend">
                <input class="password optional" id="user_password" maxlength="128" name=
                "user[password]" placeholder="Password" size="50" type="password" />
              </div>
              <span class="help-inline">can't be blank</span>
            </div>
          </div>
        </div>

如果提交时存在错误,我的rails代码会添加带有类"help inline"的span。。。如果没有错误,则不会将此跨度添加到输入中。。。

如何将输入占位符文本与span文本交换。。。对于表单中的每个输入。。。

例如。。。如果第一个字段出现错误,我想将占位符文本"全名"更改为"不能为空"。。。

非常感谢。。。

试试这个-

$('#user_name').prop('placeholder', function () {
    return $(this).parent().next('.help-inline').text()
});

这就是工作原理:

Javascript:

$("input").each(function() {
  if ($(this).parent().next(".help-inline").text().length) {
    $(this).prop("placeholder", $(this).parent().next(".help-inline").text());
    return $(this).val("");
  }
});

Coffeescription:

$("input").each ->
    if $(this).parent().next(".help-inline").text().length
      $(this).prop "placeholder", $(this).parent().next(".help-inline").text()
      $(this).val ""