I have multiple select box on my page with id's drop_01, drop_02 and so on along with a common class.
I am writing a jQuery that whenever a select box is changed, I get the number of selected options for that select box. Following is the jQuery but its not working. Can anyone tell me what am i doing wrong.
var x = "drop_" + idnum; // (idnum contains the numeric index like 01,02 etc).
var length = $(' "#" + x option:selected').length;
But when i give the hard coded id like below, it works fine.
var length = $('#drop_02 option:selected').length;
Please help.
You aren't concatenating the string of the selector properly:
var length = $('#' + x + ' option:selected').length;
I would strongly suggest you use an editor with syntax highlighting as it makes it virtually impossible to miss errors like this.
Related
I'm attempting to craft my own cloning function that changes the name of cloned inputs so they can be collected by PHP.
on W3C I found this simple function to build from
$("button").click(function(){
$("p").clone().appendTo("body");
});
I modified it to clone a fieldset with multiple inputs and it worked. I took it a step farther to try to make it rename and integer the name attribute of the different input elements and now it doesn't even clone the field.
Here's what I have so far.
$("#p20_01_yes").click(function(){
var num = $('.clonedInput').length,
newNum = new Number(num + 1);
$("#cloner").clone($("input, textarea, select").each().attr('name'+newNum)).appendTo("#page20");
});
I just tried to post a snippet of the HTML but I got a warning telling me the limit is 30,000 characters so here's a js fiddle that shows everything.
https://jsfiddle.net/Optiq/krjztsm2/
I structured the JQuery the way I did because I figured it would be more appropriate to do the renaming inside of the clone function then append the results to the page rather than appending it then going back and separating it from everything else to dig back through... figured that would make more sense to the computer. Is this the right way to look at it?
You were pretty close already. I'm not sure if my answer will work perfectly (seeing that the JSFiddle is pretty messy), but you could just adapt the classes and ids afterwards.
You just need to split your tasks into two parts:
Clone the fieldset
Update the input elements names (and possibly ids as well?)
Here is an example of how this could work:
$("#p20_01_yes").click(function(){
var num = $('.clonedInput').length,
newNum = new Number(num + 1);
var $clonedFieldset = $("#cloner").clone().appendTo("#page20");
$clonedFieldset.find("input, textarea, select ").each(function() {
var $item = $(this);
$item.attr('name', $item.attr('name') + newNum);
});
});
I'm successfully creating some dynamic input textboxes using the following javascript:
var type = "Textbox";
var foo = document.getElementById("fooBar");
for (i = 1; i <= totalQty; i = i + 1) {
var textbox = document.createElement("input");
//Assign different attributes to the element.
textbox.setAttribute("type", type + i);
//textbox.setAttribute("value", type + i);
textbox.setAttribute("name", type + i);
textbox.setAttribute("id", type + i);
textbox.setAttribute("style", "width:300px");
textbox.setAttribute("width", "300px");
//Append the element in page (in span).
var newline = document.createElement("br");
foo.appendChild(newline);
foo.appendChild(textbox);
}
Everything works fine with that. Once the user keys in data and clicks submit however, I need to go back and set the background-color of any textboxes with an error to red. I found some code to do the actual coloring:
textbox.style.backgroundColor = "#fa6767";
...and I know the exact name of the textbox with the error (i.e. "Textbox1", "Textbox2", "Textbox3", etc) but I'm not sure how to programatically assign this background color code to the specific textbox. I can't use something like this, since all code is dynamically generated:
errorTextbox = $("#Textbox1");
Any suggestions?
It looks like you're building a form validation script. Here's an easier way to do this:
1) Create an entry in your stlyesheet for your error class. Adding and removing a class requires fewer steps than assigning properties individually.
.error {
background-color: #ff0000;
}
2) Give all the textboxes you wish to validate a unique class name "valMe", for example.
3) Then loop through them during the validation step:
$('.valMe').each(function() {
$(this).removeClass('error');
if($(this).text=='') {
$(this).addClass('error');
}
})
By using "this" you refer to the current element, so you don't even need to know the ID of the element.
If you already know the name (in this case identical to the id) of the element, you can use jQuery to select the element by forming the selector using string concatenation. Assuming you have a variable that stores the name/id of the text box that has the error, then it's a relatively simple process:
var errorTextboxName = 'Textbox1';
$('#' + errorTextboxName).css('background-color', 'red');
I ended up going with the following:
document.getElementById('Textbox1'.style.backgroundColor = "#fa6767";
I originally didn't think I would be able to capture my "Textbox1" control in this fashion since when I viewed the html source code, there was no "Textbox1" due to the fact I dynamically created it.
Thanks.
Here is a simplified example of what i'm working with, working around preexisting code:
Basically I have 2 divs I want to hide/show in multiple places(stage 1, stage 2, stage 3,etc), as so:
var blue_div = "#Blue";
var red_div = "#Red";
var blue_stage = "#Blue" + count;
var red_stage = "#Red" + count;
Adding insult to injury the div's exist elsewhere on page and are hidden. Need to pull the content into another div for each stage. So i'm using .prepend() to grab the content, as so:
var blue_html = $(blue_div).html();
var new_div = "#new_div";
$(new_div).prepend(blue_html);
$(new_div).attr('id', blue_stage); //Changing the id based on the stage
That last part is really whats throwing me...As now I'm trying to use the new_div without first ending the script so it's not yet in the DOM...
if ($(blue_stage).is(':hidden')) {
$(blue_stage).show()
$("#cancel").bind("click",function(){
$(blue_stage).hide()
}
}
I've seen a lot done with Window setTimeout() as well as setinterval and .queue(). But my attempts have all failed. Hopefully my example wasn't confusing, any help at all is appreciated!
I think you can do something like this:
var $new_div = $('<div id="' + blue_stage + '"></div>');
which will allow you to edit the element directly so you can do things like:
$new_div.prepend(blue_html);
to change the id you do:
$new_div.attr('id', blue_stage)
and note when your setting the id like this you don't need the "#" as the other answer mentions
Remember that you use the hash-mark # when selecting, but when setting as an ID on a node, you just use the identifier without this mark. So this line:
$(new_div).attr('id', blue_stage); //Changing the id based on the stage
Equates to this:
$(new_div).attr('id', '#Blue' + count);
But should perhaps be like this:
$(new_div).attr('id', 'Blue' + count);
(without the hashmark).
Hopefully your problem is as easily solved! Good luck!
Please forgiving if the title is a little non-descriptive. Here is what im doing. Im making dynamic textboxes in a table using javascript. For example i add one row to the table, give the textbox a name for instance tname, i want to make each textbox unique so i add a row number to the end of it, so the textbox name is tname1, next would be tname2...etc. Now I want to create another function to loop through this table to get all of the values. Here is the code im using to get the value of the textbox below. I didnt put the for loop b/c I know that the loop works, b/c i got the correct number of rows.
txt = document.getElementById('tname' + a)
alert(txt.value)
I know that there is a function that you put around this: ('tname' + a) to let javascript know that your concatenating it together b/c i did it before just cant remember the function. If any can help, it would be very much appreciated
If you assigned the id (not name) then dirty pure JavaScript work around is:
var a = 1;
while (true) {
var id = 'tname' + a;
var txt = document.getElementById(id);
if (txt == null)
break;
alert("value of " + id + " is: " + txt.value);
a++;
}
This will keep looking for elements, until it can't find any - hope this makes sense.
You need to use ID and name. For example,
<input type="text" name="tname1" />
should be
<input type="text" name="tname1" id="tname1"/>
Use JQuery. It simplifies tasks like this:
$('input[type="text"]').map(function(){
return (this.value.length > 0) ? this.value : null;
}).get().join(',');
Working demo: http://jsfiddle.net/AlienWebguy/wLteQ/
Have you tried:
var els = document.getElementsByName(...);
// Or if you only focusing on newer browsers:
var els = document.querySelectorAll(..);
// els is now a HTMLCollection / NodeList
console.log(els[0].value);
I want save multiple individual records for a single model. So my form will have <input> elements with IDs that look like this Author0Title; Author1Title; Author2Title, etc.
I will be getting values for these input's using jQuery.getJSON() method.
I want to assign individual values for these input like these automatically.
document.getElementById('Author0Title').value = respose.data[0].title;
something like..
for(i=0;i<response.data.length; i++){
var id = 'Author' + i + 'Title';
document.getElementById(id).value = respose.data[0].title;
}
But it is not working. I appreciate any help.
Thanks.
If you're using jQuery:
for (var i = 0; i < response.data.length; i++) {
$('#Author' + i + 'Title').val(response.data[i].title);
}
That's pretty close to your example, except that you've got '0' coded in as the index instead of 'i'.
Make sure that your <input> elements really are using both an "id" and a "name" that's constructed as you expect. If they're just getting the "name" attribute set, you could do this:
$('input[name=Author' + i + 'Title]').val(response.data[i].title);
Could it be that you're misspelling respose -> response?
Otherwise, "should work". Assuming your JSON actually matches what you're looking for in this code.
Since you're using jQuery, you might want to use $('#Author' + i + 'Title').val(response.data[i].title); instead - although it does the same.