jdoe jdoe - 1 year ago 159
Javascript Question

jQuery - append string to input when changed

I have multiple select inputs on a page and I'd like to set all of them to have a particular option selected if a checkbox is checked

Once the form is submitted the inputs that have been updated will be looped through and sent to the database, so I have a function to append a string to the option value which is called on change of the select

This is all working great, however I'd like to append the updated string (to the value, not text) when the select option is changed by the checkbox being checked, but can't seem to get this to work

Fiddle https://jsfiddle.net/69zzr6xa/2/

I've tried looping through each select like so and then checking if the second option is already selected. If not, append the string, but it doesn't appear to work

$('select').each(function() {
if (!$(this).$('option').text == 'Two') {

var inputname = $(this).find(":selected")[0].value;

$(this).(":selected").val(inputname + "-updated");


Answer Source

I think this is what you are looking for.

function set_to_two() {

    $(this).prop('selected', true);
    if( $(this).val().indexOf('-updated') < 0 ){
        $(this).val( $(this).val() + "-updated" );


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download