0

I'm trying to pass a changing variable to jquery function below but missing a piece.

 $(document).ready(function(){ 
 var area = "NW";
 $("#NWbutton").click(function (){
 $('#mainmap > img').attr('src', "some_web_"+area+"_address_forpics_time.gif");
 });
});

For the "NWbutton" I need var area = "NW". I have 20 or so buttons with corresponding variables. How do I pass these for each button instead of writing out each variable?

asked Aug 10, 2014 at 16:08
3
  • You could use an array for your area, and loop on them. Commented Aug 10, 2014 at 16:10
  • 1
    how are you using selector, I think there should be either #NWbutton or .NWbutton or button? what is just NWbutton? Commented Aug 10, 2014 at 16:12
  • Yes it should read ("#NWbutton") Commented Aug 11, 2014 at 12:47

2 Answers 2

1

data attributes provide the perfect solution to this problem. You can put whatever data is related to that button into the attribute, which you can then read in the click handler. Something like this:

<div id="mainmap">
 <img src="foo.jpg" data-area="NW" />
 <img src="bar.png" data-area="SW" />
</div>
$("#NWbutton").click(function (){
 $('#mainmap > img').attr('src', function() {
 return "some_web_" + $(this).data('area') + "_address_forpics_time.gif";
 });
});
answered Aug 10, 2014 at 16:12
Sign up to request clarification or add additional context in comments.

Comments

0

Following Rory McCrossan , individual button's or input[type=button]'s could includetext or value corresponding to selection variable for that element, i.e.g.,

<button>NW</button>

or

<input type="button" value="NW" />

html

<div id="mainmap">
 <img src="foo.jpg" alt="NW"/>
 <img src="bar.png" alt="SW"/>
 <img src="baz.jpg" alt="NE"/>
 <img src="foobar.png" alt="SE"/>
</div>

js

$(document).ready(function() { 
 // with `input` elements , substitute
 // `input[type='button']` , `$(e.target).val()`
 // for `button` , `$(e.target).text()` , respectively
 $("button").click(function (e) {
 var area = $(e.target).text();
 $('#mainmap > img[alt='+ area +']')
 .attr('src', "some_web_" 
 + area
 + "_address_forpics_time.gif");
 // console.log($("img[alt='" + area + "']").attr("src"))
 }); 
});

jsfiddle http://jsfiddle.net/guest271314/hphe11qu/

answered Aug 10, 2014 at 18:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.