0

I have a web form with a hidden input field as follows:

<input id="requiredFields" name="requiredFields" type="hidden" value="firstname,lastname,email,phone">

I want to add and remove ",location" based on a certain condition using jQuery as follows:

$('input[name="locationstatus"]:radio').on("change", function() {
    if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') {
        /* need syntax to append text ',location' to #requiredFields string */
    }
    else {
        /* need syntax to remove text ',location' from #requiredFields string */
    }
});

Thanks

3 Answers 3

3

Using jQuery's .val() to update the value of requiredFields

$('input[name="locationstatus"]:radio').on("change", function() {
    if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') {
        $('#requiredFields').val($('#requiredFields').val() + ',location');
    }
    else {
        $('#requiredFields').val($('#requiredFields').val().replace(',location',''));
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

This looks streamlined @Sharlike. I am going to test it now and post back.
Perfect @Sharlike -- exactly what I needed. As soon as SO allows me to accept this as the answer I will do so
@H.Ferrence Glad it was what you needed
0

Rather than trying to append/remove the one part of the string, it would probably be easier and faster to just replace the entire string, assuming that there are no other strings, in which case I can offer a more robust solution.

$('input[name="locationstatus"]:radio').on("change", function() {
    if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') {
        /* need syntax to append ',location' to #requiredFields */
        $('#requiredFields').val('firstname,lastname,email,phone,location');
    }
    else {
        /* need syntax to remove ',location' from #requiredFields */
        $('#requiredFields').val('firstname,lastname,email,phone');
    }
});

Comments

0

If you want to append the location to the end you can use the .val() method. It is also capable of setting the value of an element.

 $('input[name="locationstatus"]:radio').on("change", function() {
   if ($('input[name="locationstatus"]:radio:checked').val() == 'Yes') {
      var prev = $("#requiredFields").val();
      $("#requiredFields").val(prev + ',location');
   }
   else {
    var newText = $("#requiredFields").val().replace(',location', '');
    $("#requiredFields").val(newText);
   }
 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.