Getting a dynamic textbox name using javascript - javascript

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);

Related

Get Unsorted list list items that are added dynamically in the Controller

I am working on a project (MVC) with Razor views.
I am trying to populate a list dynamically (trying with ul/li but the select/option would also be fine) with a click on a button. The user is filling in a field, clicks a "add" button and this adds it to a ul/li structure.
When I am looking at the inspect element, I can see my values being added, my issue is to store them into Session["..."] ... Or in a hidden field so that I can iterate on them in the Controller action.
I tried several JS/Jquery answers from the net but none of them seemed to work in my case.
Here is how I populate the ul/li structure:
function addPrice() {
var priceValue = $("#PriceValue").val() // this is the input that users fill in
var ul = document.getElementById("priceListBox");
var li = document.createElement("li");
li.setAttribute('class', "list-group-item list-group-item-action"); // set the class for design
li.setAttribute('id', priceValue); // set the id to be able to remove
li.appendChild(document.createTextNode(priceValue));
ul.appendChild(li);
}
Above correctly populates a ul with list items holding the value of the user input.
This is my hidden field attempt:
<input type="hidden" name="PriceValues" value="" runat="server"/>
This is my predefined ul:
<ul class="list-group col-md-3" id="priceListBox" name="priceListBox" runat="server"> </ul>
This is the latest attempt I tried to build up my array and access these values in the controller action:
function SetItemsToArray() {
//const listItems = document.querySelectorAll('li');
//for (let i = 0; i < listItems.length; i++) {
// alert(listItems[i].textContent);
//}
var listItems = document.getElementById('priceListBox').getElementsByTagName('li'), myArray = map(listItems, getText);
function map(arraylike, fn) {
var ret = [], i = -1, len = arraylike.length;
while (++i < len) ret[i] = fn(arraylike[i]);
return ret;
}
function gettext(node) {
if (node.nodetype === 3) return node.data;
var txt = '';
if (node = node.firstchild) do {
txt += gettext(node);
} while (node = node.nextsibling);
$('#PriceValues').val(txt); // Jquery attempt
document.getelementbyid("PriceValues").value = txt; // js attempt
}
}
I would like to know:
What is the best way of achieving this?
What is the quickest way of achieving this?
Why is the current attempt not working?
Thank you all for any response, if any question ask and I will do my best to reply correctly to it.
Kind regards.
Perhaps, I'm wrong but, your input hidden, has a "name" attribute, instead of id? So shouldn't you assign an id instead of a name?
So with everyones input and several attempts i have succeeded to get the values in my controller.
#joseatchang, you are totally right, good point! Thank you for pointing that out. #Andreas, you are correct as well, with alerts i can see that it stops running at the "var listItems ..." and then it doesn't run any further. I am not able to make it work neither, i changed the getElementById syntax as well but i can't get the function to work properly but i still want to know what is wrong so if you want to elaborate on that i would appreciate it greatly.
#Scott Rickman, i tried several approaches with .textContent and others but the following worked like a charm (thanks for the splitting tip as well ;)):
This worked by putting it where i add the list items dynamically:
document.getElementById("PriceValues").value += priceValue + ";";
and in my controller:
var a = Request.Form["PriceValues"];
Thank you all for helping me, i really appreciate it!
Have a good week, kind regards!

jQuery Dynamic Selector

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.

How can I update the background color of a dynamic input control?

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.

Javascript bookmarklet to click a button found by unique name

I need a javascript bookmarklet which can click on a button. The thing is, there are 100+ buttons on the page all with the same value. The name is unique but quite long.
The full name of the element is something like :
actions[http://apps.facebook.com/frontierville/giftaccept.php?next=giftaccept.php&senderId=1%3A1325206719&gh=3a8bfdace76051752a9127d1f9b43872&gift=nails&timestamp=1285598414&ref=tab&key=29b15e06ed9d7c00a8870c955ab938cf%24%24cfH1PUUZ%217bZYhg8M-o-XQc%218HHRMcvvyhuf4d%21.64qEvlQe&src=request&aff=gift&crt=nails&signature=6dd3fa03fe88f98b6dcab4faf4c7da94]
The value of every button is Accept and Play.
So. Is there a way to have it click on the button with a specific URL in the name?
Here is the source of the info for one of the buttons (got this from chrome's inspect element feature):
<input value="Accept and Play" type="submit" name="actions[http://apps.facebook.com/onthefarm/giftaccept.php?senderId=1259413693&gift=mysterygift&timestamp=1285599906&ref=gift_accept_tab&key=78fcc7de3b36b8f9564262fab506893f%24%24ceK5RVRY61bZYhg8M-o-XQcyL%2CzHccEwEeuj4e-%21-dh0AD0A2AgyScd&signature=32db959ce43f8330cf8fd992fbd53a51&srcapp=FarmVille]">
This should do it...
javascript:var nam=prompt("Give me a URL to look for"); nam="actions["+nam.replace(/\&/g, "&")+"]"; var els=document.getElementsByName(nam); if(els.length == 0) alert("Button not found"); else els[0].click();
It's based on getElementsByName, here it is all spelled out...
var nam = prompt("Give me a URL to look for");
nam = "actions[" + nam.replace(/\&/g, "&") + "]";
var els = document.getElementsByName(nam);
if(els.length == 0)
alert("Button not found");
else
els[0].click();
Here's a rough example of what you might want to do.
var url = 'http://reallylong.facebook.url.from.your.example';
var searchName = 'actions[' + url + ']';
var items = document.getElementsByName(searchName);
if (items.length > 0) {
var myButton = items[0]; // assuming the first item is the correct one
myButton.click(); // programmatically click it
}
if the url is going to change every time, you can find someway to fill the url variable, and use that to generate the element name. This example assumes that element is the only one on the page with that exact name attribute.
This example is pretty rigid and may not work as your bookmarklet if you need to interact with it. What do the other elements look like? Would it be better to look for an element pointing to the giftaccept url or something like that? The script would have a lot more flexibility in a situation like that.
For convenience and compatibility use JQuery selectors:
nameVal = 'actions[http://apps.facebook.com/onthefarm/giftaccept.php?senderId=1259413693&gift=mysterygift&timestamp=1285599906&ref=gift_accept_tab&key=78fcc7de3b36b8f9564262fab506893f%24%24ceK5RVRY61bZYhg8M-o-XQcyL%2CzHccEwEeuj4e-%21-dh0AD0A2AgyScd&signature=32db959ce43f8330cf8fd992fbd53a51&srcapp=FarmVille]'
$("input[value='Accept and Play'][name='" + nameVal + "']").click()

How to set the value for form fields

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.

Categories

Resources