如何更改帖子中传输的值?

时间:2016-06-29 08:30:03

标签: javascript jquery html post

我有这个样本

代码HTML:

  <form method="post" class="add-patient">
          <div class="col-md-12">
                <fieldset>
                    <label for="lastname">Phone<span class="star">*</span></label>
                    <input class="required-input _phone" id="primary_phone" type="text" name="phone" maxlength="10"  value="<?php echo $prInfo->clinicphone; ?>" placeholder="1234567890">
                </fieldset>
          </div>
          <div class="col-md-12">
               <div class="pull-right" id="save-bottom-add">
                    <button type="Submit" id="btn-sub" class="btn btn-primary btn-save" onclick="DoSubmit()">Submit</button>
               </div>
          </div>
   </form>

CODE JS:

function DoSubmit(){
        var firstFormat = $("#primary_phone").val();  //ex format:(123) 123-1234
        var lastFormat = firstFormat.replace(/\s/g, ''); //the new format should be: 123-123-1234
        console.log(lastFormat);
        return true;
    }

我想要做的是在提交之前转换输入的格式文本,并将其以新格式传递给POST

我们选择方法是正确的吗? 转换此格式的解决方案是什么?

你能帮我找到解决这个问题的方法吗? 提前谢谢!

2 个答案:

答案 0 :(得分:1)

这样的事情应该让你走上正轨

function DoSubmit(){
    var firstFormat = $("#primary_phone").val();  //ex format:(123) 123-1234
    var lastFormat = firstFormat.replace(/\D/g,"").replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3'); //new format: 123-123-1234
    console.log(lastFormat);
    // also do any substitution of value(s) here
    // Ex:- $("#primary_phone").val(lastFormat);
    return true;
}

$(".add-patient").submit(function() {
    DoSubmit();
});

.submit()是第一个版本中.on( "submit", handler )的快捷方式,第三个版本中是.trigger( "submit" )的快捷方式。见docs

更新:感谢@titus指出非数字字符。 请参阅更新的代码和this fiddle以获取演示。

答案 1 :(得分:0)

试试这个:

function DoSubmit(){
    var firstFormat = $("#primary_phone").val();  //ex format:(123) 123-1234
    //First, replace all non-numeric character then, replace all groups of 3 numbers (not the ending group) with the group itself fallowed by a line.
    var lastFormat = firstFormat.replace(/\D/g, "").replace(/(\d{3}(?!$))/g,"$1-"); 
    // Change the input's value to the new one.
    $("#primary_phone").val(lastFormat);
    return true;
}