Reputation: 23
I'm trying to change the label of a form box based on the selection of a radio button.
After scouring the internet, and multiple coding attempts using multiple variations of code, I've hit a brick wall, because nothing I seem to do works. So any help would be greatly appreciated.
These are the two radio buttons
<input type="radio" name="event" id="walkEvent" value="walkEvent"/><label>Walk Event</label>
<input type="radio" name="event" id="otherEvent" value="otherEvent"/><label>Event</label>
This is the label I want to change
<p><label id="place">Meeting Point/Location: </label><input type="text" name="meeting_or_location"/></p>
This is the script I have so far
<script type="text/javascript">
$(document).ready(function(){
if ($('#walkEvent').is(':checked')){
$('#place').text('Meeting Point:');
}
else if ($('#otherEvent').is(':checked')){
$('#place').text('Location:');
}
});
</script>
The idea being that if the Walk Event radio button is selected, then the label 'Meeting Point/Location:' becomes 'Meeting Point:'. Conversely, if Event is selected, 'Meeting Point/Location:' becomes 'Location:'
Yet when I use the above code, and check a radio button, nothing happens.
Upvotes: 2
Views: 2316
Reputation: 1636
You can use click
event for this,hope this helps
$("input[name='event']").click(function(){
var radioValue = $("input[name='event']:checked").val();
if(radioValue=="walkEvent")
$('#place').html('Meeting Point')
else
$('#place').html('Location')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="radio" name="event" id="walkEvent" value="walkEvent"/><label>Walk Event</label>
<input type="radio" name="event" id="otherEvent" value="otherEvent"/><label>Other Event</label>
<p><label id="place">Meeting Point / Location: </label><input type="text" name="meeting_or_location"/></p>
Upvotes: 2
Reputation: 54831
Bind listener to change
event which happens when you click on radio button:
$('[name="event"]').on('change', function() {
if ($(this).attr('id') == 'walkEvent') {
$('#place').text('Meeting point: ');
} else {
$('#place').text('Location: ');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="event" id="walkEvent" value="walkEvent"/><label>Walk Event</label>
<input type="radio" name="event" id="otherEvent" value="otherEvent"/><label>Other Event</label>
<p><label id="place">Meeting Point / Location: </label><input type="text" name="meeting_or_location"/></p>
Upvotes: 2