简体   繁体   中英

jQuery: Using replace() on value of input not working

https://jsfiddle.net/vxLurdyb/1/

When the user selects YES in the membership dropdown, the value of the input should change from "service_## ####" to "membership ##_####" which I have been trying to do with replace(), as well as make the change clearly visible to the user, but it stays the same both visually and when the form is sent.

<div class="col">
  <div class="form-group col-md-6">
    <label class="" for="membership">¿Membership?</label>
    <select name="membership" id="membership" class="form-control input-sm">
    <option value="0">NO</option>
    <option value="1">YES</option>
    </select>
  </div>

  <div class="form-group col-md-6">
    <label for="exampleInputEmail1" class="light-label">ID</label>
    <input type="text" class="form-control" name="invoice_id" id="invoice_id" value="service_id_19_0022" readonly>
  </div>
</div>
    $('#membership').change(function(e){
        if( $(e.target).val() == 1 ){
            changeServiceId();
        }
    });

    function changeServiceId(){
        $('#invoice_id').prop('readonly',false);
        var invoiceid = $('#invoice_id').val();
        console.log(invoiceid);

        var invoiceid = invoiceid.replace(/service/, 'membership');
        $('#invoice_id').attr('value').replace(/service/, 'membership');
        console.log(invoiceid);
        $('#invoice_id').prop('readonly',true);
    }

As you can see I tried both attr('value') as well as value() but it seems Im doing something wrong

The issue is you are not setting the value at all to #invoice_id . To set value we can simply use .val( value ) like:

var invoiceid = invoiceid.replace(/service/, 'membership');
$('#invoice_id').val(invoiceid);

Fiddle Demo

You're over-thinking it here:

$('#invoice_id').attr('value').replace(/service/, 'membership');

First of all, you're not actually doing anything with the value that you're replacing. ( .attr() returns a value, .replace() returns a value, ultimately that last returned value is just being ignored.) Second, use .val() to set a value. You can simplify to just this:

$('#invoice_id').val(invoiceid);

You can set the value by either one of these:

$('#invoice_id').val(invoiceid);

or using attr() like you tried to do: $('#invoice_id').attr('value', invoiceid)

Please find the modified code https://jsfiddle.net/un9v8xah/

You should change the value on dropdown change.
Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM