HTML How to pass two variables on a radio button press? - javascript

How can I pass two variables on a button press? This may seem basic but I am completely stuck!
I am creating a table that has a radio button on the left side, and when you press it I want to retrieve two values. I am currently retrieving one value but I am missing the other.
Currently I am passing one value onto my onRadioButtonPress function like this:
html += "<tr><td><center><br>
<input type='radio'
onclick='onRadioButtonPress(this.value)'
name='siteChosen'
value='"+siteIDArray[i]+"'>
<center></td>";
And I am calling the function like this:
//function for on radio button press
function onRadioButtonPress(val){
//blah blah blah
}
Which is working great, but how do I add a second value of
usagePlanArray[i]
to my on onClick function? How would I change my input?
Thank you in advance!!! :) Please let me know if you have any questions, or if I missed something that would help you out!
SOLVED!
Please see the marked answer from #mplungjan. I used his alternative method that is useful for jQuerys.

value='"+siteIDArray[i]+"|"+usagePlanArray[i]+"'>
but you need to remove the newlines from the HTML too
Then in the function you can use
var vals=val.split("|");
var siteID=vals[0], usagePlan=vars[1];
Alternative - especially useful in jQUery:
html += "<tr><td><center><br><input type='radio'"+
" onclick='onRadioButtonPress(this)' name='siteChosen'"+
" data-siteid='"+siteIDArray[i]+"'"+
" data-usageplan='"+usagePlanArray[i]+"'><center></td>";
and
function onRadioButtonPress(rad) {
var siteID=rad.getAttribute("data-siteid"),
usageplan=rad.getAttribute("data-usageplan"),
}

Pass an array in JSON:
value='"+JSON.stringify(siteIDArray)+"'>
That would pass the entire Array as JSON Array string.
Passing to single values:
value='["+siteIDArray[i] + "," + usagePlanArray[i] + "]'>
or, as an object:
value='{ \"val1\":\""+siteIDArray[i] + "\",\"val2\":\"" + usagePlanArray[i] + "\"]'>
Now decode in the function
values = JSON.parse(val);
...
xyz = values[0]; // for the array
...
xyz = values.val1; // for the object
code could even be optimized, if you direct pass that to the onclick instead of the value parameter, but that might have some additional purposes.

If you are using the same index for both arrays, why not just store the index as the value and look up the desired values in the click callback?
var html= "";
var siteIDArray = [1, 5, 2, 33];
var usagePlanArray = ["unlimited", "20gb", "10gb", "5gb" ]
function arrayCombo(index){
return {siteId: siteIDArray[index], usagePlan: usagePlanArray[index]};
}
for(var i=0; i<siteIDArray.length; i++){
html += "<tr><td><center><br><input type='radio' name='siteChosen' value="+i+"><center></td>";
}
$('#content').html(html);
$('input').on('click', function(event){
//Do whatever you want with the values you are looking for here
var x = arrayCombo(this.value);
alert(x.siteId+", "+x.usagePlan);
});
Also, to demonstrate this tight-knit relationship between your arrays it would probably be better to store their values at shared indexes as properties of objects in an array.

Related

What am I missing in the jQuery .each() function?

I have this function that I am trying to figure out/fix and can't seem to pinpoint the issue / can't figure out a way to get it working.
Basically my CMS is spitting certain hrefs that I would like to:
Part 1) change the targeted href URL
Part 2) change the button's text
Right now I only have 2 instances of this type of button, so here's what is printing out in my console:
Part 1) for this part I get the correct urls without the characters i want to strip out.
Part 2) two instances of the button's text (See All) followed by the correct variable of btnParent for the first button and then the second button and finally one instance of "Products".
My issue is, I can't figure out how to:
Part 1) send back the stripped URL to its respective button's href as an each function.
Part 2) Have the each() function print out the new text as "See All + BLAH + Products" for each instance, and then append the new text to the respective button.
Here is the code:
function viewMoreBtn() {
var btnMain = $("li:contains('See All')");
var btnText = $("li:contains('See All')").text();
var btnParent = $("li:contains('See All')").parent('ul').prev('li').text();
// PART 1 - STRIP LINK URL OF -_-// CHARACTERS
$.each(btnMain, function(i, v) {
v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(v);
});
// PART 2 - ADD LABEL TO HTML TEXT OF BTN
$.each(btnMain, function(index, value) {
value = (btnText + btnParent + 'Products');
$(btnMain).text(value);
console.log(value);
});
}
viewMoreBtn();
Thank you.
jQuery objects, as return by $(...) have a each method already on them. The element is passed as the this context. You could use that further with jQuery to act on the objects in an scoped context. Basically, you have the right code, just in the wrong scope.
Part 1
btnMain.each(function() {
var $li = $(this);
var $a = $li.find('a');
var desiredUrl = $a.attr('href').replace('-_-//', '');
$a.attr('href', desiredUrl);
});
Part 2
btnMain.each(function() {
var $li = $(this);
var btnText = $li.text();
varbtnParent = $li.parent('ul').prev('li').text();
value = (btnText + btnParent + 'Products');
console.log(value);
$li.find('a').text(value);
});
See #Zequ's answer for the iteration over the each() function in the returned btnMain.
This is how $.each( obj, function( key, value ) works: you iterate over btnMain, and for each iteration of $.each(), the function assigns the index of the iteration to i and the value of btnMain at that index to v.
$.each(btnMain, function(i, v) {
//v = $(this).find('a').attr('href').replace('-_-//', '');
console.log(i); // I am the index of $.each() iterator
console.log(v); // I am the node from the btnMain array
// I don't know if this is right without seeing your HTML, but it seems like what you want
v.find('a').attr('href').replace('-_-//', '');
});
The second $.each() follows the same pattern.
If I understood correctly, you're confusing your variables.
$.each is a function for each element of the array/object being passed. It gives you a index and the element, check the reference
In part 1, you're defining v as the string you want, you're not changing the element at all,you need something like this:
$.each(btnMain, function() {
// you're saying you got the correct URLs, so the only thing you need to do is to change the element afterwards
var element = $(this).find('a');
v = element.attr('href').replace('-_-//', '');
element.attr('href', v);
});`
Also you could use btnMain.each instead of $.each
In part 2, you are changing the value variable (it's actually the element you're iterating over), to the string you want, then you follow it by trying to change btnMain's text. This is wrong, from what I understood, btnMain is an array of two elements you can't change it's text. You should change the element's value (that you are calling value). It would be something like that
$.each(btnMain, function(index, element){
// I think this is the time you want to define the btnParent, relative to the element
var btnParent = element.parent('ul').prev('li').text();
var value = (btnText + btnParent + 'Products');
element.text(value);
}
I THINK this is what you need.
Also you could append both parts into one, since both are iterating over btnMain

jQuery form input into an array not working

I'm working on a game and there is a form input where the user enters the number of characters. Once this happens more inputs appear for each character's name. My problem right now is reading those names into an array.
When the new inputs are created also a new button called nameButton is created and that is my issue, when I attempt to click that nothing happens when the values should be stored in an array. I put a prompt at the end of the function just to check and that does not even get called.
If you all have any suggestions please let me know here is the jsFiddle
function nameRecording(names,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=names; i++)
{ var nearTr=$this.closest('tr');
addRows=addRows+'<td>Name one:</td><td><form><input type="text" name="charcItem" class = "newR"/></form></td>';
}
addRows=addRows+'<td><div class="button" id="nameButton"> Add! </div></td></tr>';
nearTr.after(addRows);
};
$('#nameButton').click(function(){
names=$(".newR").map(function(){
return $(this).val();
});
prompt(names);
});
And there are some of my functions.
Try this way:
$(".form").on('click', '#nameButton', function () {
names = $(".newR").map(function () {
return this.value;
}).get();
prompt(names);
});
You can use event delegation using on for dynamic elements
You need to do a .get() on .map() result to convert the collection object into array.
Demo

jQuery getting value from dynamic array

I have an array with divs ids (in my case its all divs ID values od parent div (#area) ):
jQuery.fn.getIdArray = function () {
var ret = [];
$('[id]', this).each(function () {
ret.push(this.id);
});
return ret;
};
var array = $("#area").getIdArray();
I need to get an array field value, something like this:
var lef = $("#array".[0]).css("left");
Taking a wild swing at it (see my comment on the question):
var array = $("#area").getIdArray();
var lef=$("#" + array[0]).css("left");
That assumes that getIdArray returns an array of strings, where each string is an id value for a DOM element, and that you want to get the left value for the first of those elements.
So for instance, if the array comes back as:
["foo", "bar", "charlie"]
then the selector created by "#" + array[0] is #foo, so you end up getting the left value for the foo element.
If you have an actual JS array within your variable array just use bracket notation to access each individual ID.
// I have the # before-hand since I'm assuming you have just the ID name
var lef = $('#' + array[0]) // this will access the 1st one in the array
I think you are looking for this :
var divYouWantToChange = $("#"+array[0]);
I try to formulate this as an answer because getIdArray is not a jquery function and we don't know what it does. If you'd like to apply a custom filter to the $("#area") collection you can do so using filter. This will return a jquery object where you can get the .css("left") from.
If you'd like to save both the id's and the left property you can do so with the following code:
var objects=[];
$("#area").filter(function(){
$this=$(this);//cache the object
objects.push({id:$this.attr("id"),
left:$this.css("left")
};
});
console.log(objects);

How can I combine JQuery selectors and variables to shorten code for easier scaleability?

I have this piece of javascript that is working.
var footerColour = $.color.extract($("div#one.footer"), 'background-color');
var newrgba = $.color.parse(footerColour).add('a', -0.5).toString()
$("div#one.footer").css("background-color", ''+ newrgba +'');
var navColour = $.color.extract($("div#two.nav"), 'background-color');
var newrgba1 = $.color.parse(navColour).add('a', -0.5).toString()
$("div#two.nav").css("background-color", ''+ newrgba1 +'');
It is checking two different divs for a colour and changing the css colour value with the returned colour from a jQuery colour plugin that I have. I plan to continue to add more of these, but figured this could probably be written out in a more compact or combined way to allow for more items to be added without repeating the same three lines of code each time.
I have looked into arrays, but have been unable to find the exact answer and syntax to help with this. Any ideas? Thanks.
You can put the colour change stuff in a function and then call the function with each id (or selector) that you want to apply it to:
function changeBackground(selector) {
var footerColour = $.color.extract($(selector), 'background-color');
var newrgba = $.color.parse(footerColour).add('a', -0.5).toString();
$(selector).css("background-color", ''+ newrgba +'');
}
changeBackground("div#one.footer");
changeBackground("div#two.nav");
changeBackground("add other item here");
// or pass them all at once
changeBackground("div#one.footer, div#two.nav, etc");
// or give them all a common class and pass that
changeBackground(".someCommonClass");
If you used the latter options to update all at once you should probably loop through each item matching the selector and update them one by one (otherwise either it wouldn't work or they'd all end up with the same colour):
function changeBackground(selector) {
$(selector).each(function() {
var footerColour = $.color.extract($(this), 'background-color');
var newrgba = $.color.parse(footerColour).add('a', -0.5).toString();
$(this).css("background-color", ''+ newrgba +'');
});
}
Note: given that ID is supposed to be unique, you can select just on the id. so $("#one") instead of $("div#one.footer") - unless you want to select on that id only when it has the "footer" class.
Just add a common class to the elements which need to see these changes and use the following code:
Assuming common class is 'changeBG'
jQuery('.changeBG').each(function() {
var navColor = jQuery.color.extract(jQuery(this), 'background-color');
var newRGBA = jQuery.color.parse(navColor).add('a', -0.5).toString();
jQuery(this).css("background-color", ''+ newRGBA +'');
});
This should solve shorten your code.
I would do something like this:
function changeColor(arr, colorType){
// Define length of array
var i = arr.length;
// Loop over each item in array
while(i--){
// Create jQuery object with element from array
var $elem = $( arr[i] );
// Run the color change logic
var color = $.color.extract($elem, colorType);
var newColor = $.color.parse(color).add('a', -0.5).toString();
$elem.css(colorType, newColor);
}
}
// Array of jQuery selectors
var elems = ["div#one.footer","div#two.nav"];
// Pass array and color type to changeColor function
changeColor(elems, "background-color");
This function takes an array of strings that must be valid jQuery selectors and a colorType which could be anything with color (I assume your plugin supports more than just background-color).
EDIT
Ooops, I had an incorrect variable name in there. It was $elem.css(colorType, color); but it should have been $elem.css(colorType, newColor);.
Anyway, this function gives you greater flexibility because you can change the color type in the function call. You would execute one function per array and just specify a color type. You could easily add another parameter for colorChange to handle the 'a', -0.5 part.
This method also results in fewer function calls which would likely make it faster than the other solutions here.

How can one put together multiple arrays into one string?

I'm having a hard time describing what I'm looking for.
If we pretend that we're pulling an array (I've used the .split to get user input data)
where each line represents a link.
How can I then add an anchor tagg to that link that I'm pulling?
I need to be able to put
< a href=" + thearray + ">anything< /a>.
The reason for this is that I'm dynamically creating a list.
I think that if I create two variables, one with this part
< a href="
one with the closing
and then call some sort of function that puts those two and the pulled array in between them until the list is complete.
Does this make any sense?
edit:
here's a link to the full code:
http://hem.bredband.net/noor/thecode.txt
I think you mean this:
for(var x=0;x<thearray.length;x++) {
document.write 'anything'
}
You just want to loop through the array elements, wrapping them in some HTML.
Do you mean that you want to have an array like
["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"]
and you want to turn it into
"<a href='http://www.google.com'>anything</a>
<a href='http://www.yahoo.com'>anything</a>
<a href='http://www.stackoverflow.com'>anything</a>"
?
If so, you can just do
var myArray = ["http://www.google.com", "http://www.yahoo.com", "http://www.stackoverflow.com"];
var result = "";
for (var i=0; i<myArray.length; i++) {
result += "<a href='" + myArray[i] + "'>anything</a>";
}
If not, thinking about "I want to start with X and end up with Y", with specific examples, might help you clarify your question.
Perhaps you mean something like this:
var tagStart = '<a href="',
tagEnd = '">anything</a>',
html = tagStart + thearray.join(tagEnd + tagStart) + tagEnd;
I would still suggest using a loop, though, since the code above will be unkind if thearray is empty.
I think using map and then join is going to be more readable:
function makeLink(url)
{
return "anything";
}
result = myArray.map(makeLink).join("\n");
More info about map is available at http://www.tutorialspoint.com/javascript/array_map.htm

Categories

Resources