ace ace - 7 months ago 9
Javascript Question

Change submit button text based on radio-button value

How to change submit button text based on which radio-button is active?

Here is my code, but it does not work. It changes text only once.

I have two radio-buttons:

<input type="radio" name="build-team" class="choose" value="build" /> Yes
<input type="radio" name="build-team" class="choose" value="show" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>


And I have script:

$(document).on('click', '.choose', function() {
var target = $('.show-result');
if ($(this).attr('checked') == 'checked') {
target.html(target.data('chooseyes'));
}
else {
target.html(target.data('chooseno'));
}
})


JSFiddle example

Answer

$(document).on('click', '.choose', function() {
    var target = $('.show-result');
      target.html($(this).val());
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="build-team" class="choose" value="Yes" /> Yes
<input type="radio" name="build-team" class="choose" value="No" /> No
<button class="show-result" data-chooseyes="Yes" data-chooseno="No">Yes</button>