Using jquery to update onSelect ()

I have some HTML that I would like to change based on which of the 3 radio buttons the user clicks.

Here are the radio buttons:

<input type="radio" name="awardSwitch" value="silver" /> <input type="radio" name="awardSwitch" value="gold" /> <input type="radio" name="awardSwitch" value="platinum" /> 

The HTML I want to update is below:

 <div id="BestCourseforyourGolfGame"> <div class="floatleft"> <textarea name="code" cols="50" rows="6"> <a href="http://foo.com/best/best-of/#BestCourseforyourGolfGame" target="_blank"> <img src="http://foo.com/assets/awards/2010/best-of-2010-silver.jpg" alt="Best Course for your Golf Game" border="0" width="151" height="200" /></a> </textarea> </div> <div class="floatright"> <img src="http://foo.com/assets/awards/2010/best-of-2010-silver.jpg" alt="Best Course for your Golf Game" border="0" width="151" height="200" /> </div> </div> 

Basically what I want to change, text wise in HTML, is the last bit of the image name. In this case, it is "-silver", but I would like it to be updated to "-gold" or "-platinum" depending on the button selected.

Thanks in advance!

+4
source share
3 answers

You specify jQuery, so here is the code that accesses both textarea and the display div :

 jQuery(document).ready(function(){ jQuery('input[name=awardSwitch]:radio').click(function(){ var newsrc = 'http://foo.com/assets/awards/2010/best-of-2010-'+jQuery(this).val()+'.jpg' var newhtml = '<a href="http://foo.com/best/best-of/#BestCourseforyourGolfGame" target="_blank">'; newhtml += '<img src="'+newsrc+'.jpg"'; newhtml += ' alt="Best Course for your Golf Game" border="0" width="151" height="200" /></a>'; jQuery('#BestCourseforyourGolfGame textarea[name="code"]').val(newhtml); jQuery('#BestCourseforyourGolfGame .floatright img').attr('src', newsrc); }); }); 
+4
source

Assuming you are using jQuery .

 $("[name='awardSwitch']").click(function(){ var active_value = $(this).val(); // replace the img src $("#BestCourseforyourGolfGame img").each(function(){ var src = $(this).attr("src"); src = src.substr(0, src.lastIndexOf("-")+1); $(this).attr("src", src + active_value + ".jpg"); }); }); 

"I have not tested it, I just proved it right" -Knuth

+2
source

Try something like this:

 $(function () { $("[name=awardSwitch]").change(function () { var txtArea = $("[name=code]"); var txtVal = txtArea.val(); var prevTag = txtArea.data("prevTag"); if (!prevTag || prevTag.length < 1) { prevTag = "silver" } var imgVal = $(this).val(); txtVal = txtVal.replace(prevTag+".jpg", imgVal+".jpg") txtArea.val(txtVal); txtArea.data("prevTag", imgVal); }); }); 
+1
source

Source: https://habr.com/ru/post/1337842/


All Articles