使用span text jquery交换输入占位符文本

时间:2013-06-27 15:47:47

标签: javascript jquery ruby-on-rails forms coffeescript

我有问题,如何将输入占位符文本与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代码会将“span-help”类添加为span ...如果没有错误,则此范围不会添加到输入中...

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

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

非常感谢......

2 个答案:

答案 0 :(得分:1)

试试这个 -

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

答案 1 :(得分:0)

这是有用的:

Javascript:

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

Coffeescript:

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