How to get all radio buttons inside a table? - javascript

i have group of radio buttons inside a table along with other inputs in this table, and i can't get the radio buttons by id or name or by tag name, i want to get them by type if this possible, because id and name is auto generated by JSF, and i don't want to change this.
so the requirement is: get all radio buttons only (not all inputs) inside the table so i can loop on them.

I hope there's only one set of radio buttons. In that case something like this can help:
var inputs = yourForm.elements;
var radioes = [];
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radioes.push(input[i]);
}
}​
In case there are more than one set of radio buttons, better approach would be to have a dictionary with the name as the key and the value as the array of radio buttons in the group.

I know the question doesn't mention jQuery, but I just wanted to demonstrate the simplicity of it; please consider this more of a selling point of "hey, look how nice jQuery is".
// look how pretty I am
var radioButtons = $('table#MyTableId input[type="radio"]');

Given your form name is yourForm ... (<form name = "yourForm">) ... an easy way is just to parse all form elements and check for the type, something like this:
var your_namespace = {};
your_namespace.your_function = function() {
var l = document.yourForm.elements.length;
for (i=0; i<l; i++) {
var type = yourForm.elements[i].type;
if (type=="radio") alert("Form element " + i + " is a radio!");
}
}
Instead of alerting you can ofc do alot of other things with the element id.
You can have this way easier when using a framework like MooTools or JQuery.

Related

Possibility to select specific input fields javascript

I will show you guys what I got with jsfiddles because it makes it easier to explain.
This is what kind of form setup im running right now. (Just showing you some fields, not all)
http://jsfiddle.net/XK99Z/2/
When you change the number in one of the input fields the price will immediately change too.
It uses this piece of JS for that:
function changeTotalFromCount(input) {
var unitPrice = parseFloat(input.getAttribute("data-unitPrice"));
var count = input.value;
var price = unitPrice * count;
var formattedPrice = '\u20ac ' + price.toFixed(2);
var label = input.parentNode.nextElementSibling;
label.innerHTML = '';
label.appendChild(document.createTextNode(formattedPrice));
}
When they press the submit button they will be taken to another page where the order is with their personal details, a print button and a change order button. If they press the change order button they will go back to the page like this:
http://jsfiddle.net/KPfUT/
And as you can see the price won't show next to the number anymore, but someone helped me find a solution for this problem:
function initTotals() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
changeTotalFromCount(inputs[i]);
}
}
window.onload = initTotals;
http://jsfiddle.net/7LKf7/2/
Now there is one problem, it won't work together with other input fields, like name, phone number, adres, etc.
http://jsfiddle.net/Af724/1/
I was hoping someone could help me find a solution to this maybe let JS know i only want it to run for input type="number" since all the personal details input fields are text.
I'm nowhere near experienced in JS so please let me know if you don't understand my question or you need some more information, thanks in advance!
Use document.querySelectorAll() to only select the type="number" input elements:
var numberInputs = document.querySelectorAll('input[type="number"]');
for (var i = 0; i < numberInputs.length; i++) {
changeTotalFromCount(numberInputs[i]);
}
or check the elements for their type:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].getAttribute('type') == 'number')
changeTotalFromCount(inputs[i]);
}

How to set input field maxlength from label

I'm trying to figure out a way to change the maxlength of ajax called input fields by pulling the value to set out of the field's label and updating the default value. The field labels all follow the same format - id, class, type and maxlength. The new maxlength value to set is always present in the id ...max_X_characters...
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029" class="gwt-
TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
So in this example I need to set the maxlength to 4.
The other problem is that there are multiple input fields, often with different maxlength values. See here for an example.
I was thinking of setting a script to pull out the value once the fields have loaded, but I don't mind admitting it, this one's over my head - hopefully one of you bright guys n gals can figure it out!
Update: Thanks for the suggestions, I've tried both, in various combinations, but can't get them to work.
Here's the code suggested by Ecwid's tech team that sets all input fields on the page to one maxlength (6 in this case)
`Ecwid.OnPageLoaded.add(function(page){if (page.type == "PRODUCT") {
$("input.ecwid-productBrowser-details-optionTextField").attr('maxlength','6');
};
})`
However, as I stated there are input fields with different maxlengths for some products.
I've tried replacing the '6' above with a function, based on your suggestions, to get the maxlength from the input id, but can't get it to work.
Any more ideas?
Thanks
Update:
Cracked it (nearly), here's the working code
`Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});`
Thanks so much for your help, it works like a dream on the product page but there is another area where it doesn't. A customer can edit the input text via a pop-up, from the shopping basket.
The fields have similar code:
`<input id="ecwid-productoption-16958710-Line_5_:0028max_4_characters:0029"
class="gwt-TextBox ecwid-productBrowser-details-optionTextField ecwid-productoption-
Line_5_:0028max_4_characters:0029" type="text" maxlength="200"></input>`
Suggestions very welcome
Chris
UPDATE:
Many, many, many thanks to ExpertSystem (you genius you!) - I think we've got it. (tested on IE10, firefox 21, chrome 27).
The code below is for people using Yola and Ecwid together, but I guess the original code may work for people using other sitebuilders. It limits the number of characters a user can enter into input fields, in Ecwid, by checking for a number in the input field's title (in this case the value between 'max' and 'characters') and replacing that as the field's maxLength value. It limits fields in the product browser, in the html widgets and in the cart pop-up.
Here it is:
Go to Yola's Custom Site Tracking Code section. In the 'Footer Code' column (actually placed at the bottom of the 'body'), place this code:
<script>
Ecwid.OnPageLoaded.add(function(page){
var regex = new RegExp("max_(\\d+)_characters");
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
});
</script>
<script>
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
};
</script>
and this into the 'Header Code' column:
<script>
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
</script>
That's it! You're good to go.
It is not exactly clear what is meant by "ajax called input fields", but supposing that the input fields are created and added to DOM inside a success callback for some AJAX call, you can place the following piece of code in your pages <head>:
var regex = new RegExp("max_(\\d+)_characters");
function fixMaxLength(container) {
var inputs = container.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var inp = inputs[i];
if (regex.test(inp.id)) {
var newLimit = inp.id.match(regex)[1];
inp.maxLength = newLimit;
}
}
}
And then, at the end of the AJAX call's "onSuccess" callback, append this:
fixMaxLength(document);
UPDATE:
Based on your comments below, if you need to apply fixMaxLength() to div's of class "popupContent", which get dynamically added to your DOM, an easy way (not the most efficient though) would be adding a listener for DOM modification events (e.g. somewhere in <head>):
document.addEventListener("DOMNodeInserted", function() {
var popups = document.getElementsByClassName("popupContent");
for (var i = 0; i < popups.length; i++) {
fixMaxLength(popups[i]);
}
});
(NOTE: I have only tested it on latest versions of Chrome and Firefox, so I am not really sure for which other/older browsers this does work.)
(NOTE2: GGGS, has tested it (and found it working) on IE10 as well.)
How about a regular expression on your id attribute? Such as the following:
jQuery('input').each(function() {
var idVal = jQuery(this).attr('id');
var regex = /max_(\d+)_characters/g;
var result = regex.exec(idVal);
var length = result[1];
});
This is a loop over all the inputs. Once this is run, the length variable will have the proper length each go through, for your next step.

how to get selected radio button from radiobuttonlist in javascript [duplicate]

I have an ASP.NET web page with a databound RadioButtonList. I do not know how many radio buttons will be rendered at design time. I need to determine the SelectedValue on the client via JavaScript. I've tried the following without much luck:
var reasonCode = document.getElementById("RadioButtonList1");
var answer = reasonCode.SelectedValue;
("answer" is being returned as "undefined")
Please forgive my JavaScript ignorance, but what am I doing wrong?
Thanks in advance.
ASP.NET renders a table and a bunch of other mark-up around the actual radio inputs. The following should work:-
var list = document.getElementById("radios"); //Client ID of the radiolist
var inputs = list.getElementsByTagName("input");
var selected;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
selected = inputs[i];
break;
}
}
if (selected) {
alert(selected.value);
}
Try this to get the selected value from the RadioButtonList.
var selectedvalue = $('#<%= yourRadioButtonList.ClientID %> input:checked').val()
I always View Source. You will find each radio button item to have a unique id you can work with and iterate through them to figure out which one is Checked.
Edit: found an example. I have a radio button list rbSearch. This is in an ascx called ReportFilter. In View Source I see
ReportFilter1_rbSearch_0
ReportFilter1_rbSearch_1
ReportFilter1_rbSearch_2
So you can either loop through document.getElementById("ReportFilter1_rbSearch_" + idx ) or have a switch statement, and see which one has .checked = true.
RadioButtonList is an ASP.NET server control. This renders HTML to the browser that includes the radio button you are trying to manipulate using JavaScript.
I'd recommend using something like the IE Developer Toolbar (if you prefer Internet Explorer) or Firebug (if you prefer FireFox) to inspect the HTML output and find the ID of the radio button you want to manipulate in JavaScript.
Then you can use document.getElementByID("radioButtonID").checked from JavaScript to find out whether the radio button is selected or not.
The HTML equivalent to ASP.NET RadioButtonList, is a set of <input type="radio"> with the same name attribute(based on ID property of the RadioButtonList).
You can access this group of radio buttons using getElementsByName.
This is a collection of radio buttons, accessed through their index.
alert( document.getElementsByName('RadioButtonList1') [0].checked );
function CheckRadioListSelectedItem(name) {
var radioButtons = document.getElementsByName(name);
var Cells = radioButtons[0].cells.length;
for (var x = 0; x < Cells; x++) {
if (document.getElementsByName(name + '_' + x)[0].checked) {
return x;
}
}
return -1;
}
For a 'RadioButtonList with only 2 values 'yes' and 'no', I have done this:
var chkval=document.getElemenById("rdnPosition_0")
Here rdnposition_0 refers to the id of the yes ListItem. I got it by viewing the source code of the form.
Then I did chkval.checked to know if the value 'Yes' is checked.
I would like to add the most straightforward solution to this problem:
var reasons= document.getElementsByName("<%=RadioButtonList1.UniqueID%>");
var answer;
for (var j = 0; j < reasons.length; j++) {
if (reason[j].checked) {
answer = reason[j].value;
}
}
UniqueID is the property that gave you the name of the inputs inside the control, so you can just check them really easily.
I've tried various ways of determining a RadioButtonList's SelectedValue in Javascript with no joy. Then I looked at the web page's HTML and realised that ASP.NET renders a RadioButtonList control to a web page as a single-column HTML table!
<table id="rdolst" border="0">
<tr>
<td><input id="rdolst_0" type="radio" name="rdolst" value="Option 1" /><label for="rdolst_0">Option 1</label></td>
</tr>
<tr>
<td><input id="rdolst_1" type="radio" name="rdolst" value="Option 2" /><label for="rdolst_1">Option 2</label></td>
</tr>
</table>
To access an individual ListItem on the RadioButtonList through Javascript, you need to reference it within the cell's child controls (known as nodes in Javascript) on the relevant row. Each ListItem is rendered as the first (zero) element in the first (zero) cell on its row.
This example loops through the RadioButtonList to display the SelectedValue:
var pos, rdolst;
for (pos = 0; pos < rdolst.rows.length; pos++) {
if (rdolst.rows[pos].cells[0].childNodes[0].checked) {
alert(rdolst.rows[pos].cells[0].childNodes[0].value);
//^ Returns value of selected RadioButton
}
}
To select the last item in the RadioButtonList, you would do this:
rdolst.rows[rdolst.rows.length - 1].cells[0].childNodes[0].checked = true;
So interacting with a RadioButtonList in Javascript is very much like working with a regular table. Like I say I've tried most of the other solutions out there but this is the only one which works for me.
I wanted to execute the ShowShouldWait script only if the Page_ClientValidate was true. At the end of the script, the value of b is returned to prevent the postback event in the case it is not valid.
In case anyone is curious, the ShouldShowWait call is used to only show the "please wait" div if the output type selected is "HTML" and not "CSV".
onclientclick="var isGood = Page_ClientValidate('vgTrxByCustomerNumber');if(isGood){ShouldShowWait('optTrxByCustomer');} return isGood"
To check the selected index of drop down in JavaScript:
function SaveQuestion() {
var ddlQues = document.getElementById("<%= ddlQuestion.ClientID %>");
var ddlSubQues = document.getElementById("<%=ddlSecondaryQuestion.ClientID%>");
if (ddlQues.value != "" && ddlSubQues.value != "") {
if (ddlQues.options[ddlQues.selectedIndex].index != 0 ||
ddlSubQues.options[ddlSubQues.selectedIndex].index != 0) {
return true;
} else {
return false;
}
} else {
alert("Please select the Question or Sub Question.");
return false;
}
}
reasonCode.options[reasonCode.selectedIndex].value
From here:
if (RadioButtonList1.SelectedIndex > -1)
{
Label1.Text = "You selected: " + RadioButtonList1.SelectedItem.Text;
}

Attaching change() even listeners to select/dropdown dynamically

I'm creating 3 dropdowns/select boxes on the fly and insert them in the DOM through .innerHTML.
I don't know the ID's of the dropdowns until I created them in Javascript.
To know which dropdowns have been created, I create an array where I store the ID's of the dropdowns I have created.
for(var i=0; i<course.books.length; i++)
{
output+="<label for='book_"+course.books[i].id+"'>"+ course.books[i].name +"</label>";
output+="<select id='variant"+course.books[i].id+"' name='book_"+course.books[i].id+"'>";
output+="<option value='-'>-- Select one --</option>";
for(var j=0; j<course.books[i].options.length; j++)
{
output+="<option value='"+course.books[i].options[j].id+"'>"+course.books[i].options[j].name+"</option>";
}
output+="</select>";
}
Now I have an array with 3 id's like:
dropdown1
dropdown2
dropdown3
What I want to accomplish with Javascript (without using jQuery or another framework) is to loop over these 3 dropdowns and attach a change event listener to them.
When a user changes the selection in one of these dropdown, I want to call a function called updatePrice for example.
I'm a bit stuck on the dynamic adding of event listeners here.
Now you have added your code its straight forward and you can ignore my verbose answer !!!
output+="<select id='variant"+course.books[i].id+"' name='book_"+course.books[i].id+"'>";
could become :
output+="<select onchange="updatePrice(this)" id='variant"+course.books[i].id+"' name='book_"+course.books[i].id+"'>";
This will call the updatePrice function, passing the select list that changed
However
IMO its far better (from a performance point of view for a start) to create elements in the DOM using the DOM.
var newSelect = document.createElement("select");
newSelect.id = "selectlistid"; //add some attributes
newSelect.onchange = somethingChanged; // call the somethingChanged function when a change is made
newSelect[newSelect.length] = new Option("One", "1", false, false); // add new option
document.getElementById('myDiv').appendChild(newSelect); // myDiv is the container to hold the select list
Working example here -> http://jsfiddle.net/MStgq/2/
You got the array already? Then you can do this:
function updatePrice()
{
alert(this.id + " - " + this.selectedIndex);
}
var list = ["dropdown1", "dropdown2"];
for(var i=0;i<list.length;i++)
{
document.getElementById(list[i]).onchange = updatePrice;
}
Fiddle: http://jsfiddle.net/QkLMT/3/
That won't work across browsers.
You'll want something like
for(var i = 0; i < list.length; i++)
{
$("#"+list[i]).change(updatePrice);
}
in jquery.

javascript dropdown to change all dropdown in table

I have a requirement of changing all dropdown values in all the rows in a tale based on master dropdown. say someone selects "value 2" in dropdown1, dropdown2 values in all the rows in the table should show "value2".
function change(){
var cid = document.frm.locdropdown.selectedIndex;
document.frm.locdropdown2.selectedIndex = cid;
}
is the java script I use to change it but this changes only first row.
please help..
From your example code it looks like you've given the same ID to all your locdropdown2 elements? Maybe you should post an example of your table HTML. It's normal practice to give unique IDs to elements, so you may want to test the NAME attribute instead, but anyway something like the following should work:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var inputs = document.getElementsByTagName("input");
for (var i=0, l = inputs.length; i < l; i++) {
if (inputs[i].id == "locdropdown2")
inputs[i].selectedIndex = cid;
}
}
Another option is to loop through each row in the table. The following example assumes your locdropdown2 inputs are the only thing in the third column, but you can adapt to suit your actual layout:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var tableRows = document.getElementById("yourTableId").tBodies[0].rows;
for (var i=0, l=tableRows.length; i < l; i++) {
tableRows[i].cells[2].firstChild.selectedIndex = cid;
}
}
Note: I haven't actually tested any of that code, but it should be more than enough to get you started and you can tweak as needed. (You can use Google to learn about tBodies, rows, cells, firstChild, etc.)

Categories