Forum Moderators: open

Message Too Old, No Replies

Jquery query

simple function to display different message depending on radio clicked

         

le_gber

6:05 pm on Dec 5, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi guys,

I want to update the value of a button depending on the radio button clicked. Is the following the best / most concise way of doing it?

var myForm = $('#theformid');
var draftStatus = $(myForm).find('#draft');
var finalStatus = $(myForm).find('#final');
var theButton = $(myForm).find('#save');

$(draftStatus).on('click', function(){if($(theButton).val()!='Save'){$(theButton).val('Save')};});

$(finalStatus).on('click', function(){if($(theButton).val()!='Publish'){$(theButton).val('Publish')};});


It's working, but I just wondered if there wasn't a cleverer way of doing it.

Fotiman

9:53 pm on Dec 5, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Here's a couple different ways.


function setButtonValue() {
$(this.form).find('#save').val(this.id === "draft"? 'Save': 'Publish');
}
$('#theformid').find('#draft').on('click', setButtonValue).end().find('#final').on('click', setButtonValue);


Or, if your radio buttons have the same name attribute (but different id's):

function setButtonValue() {
$(this.form).find('#save').val(this.id === "draft"? 'Save': 'Publish');
}
$('#theformid').find('input[name="radioname"]').on('click', setButtonValue);


Alternatively, you could give both radio buttons the same class and search on that.

Just make sure your end result is not so clever that you can't understand it later on. :)

le_gber

10:26 am on Dec 8, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



ty Fotiman, wasn't aware of the jquery .end(), that's going to be a tremendous help :)