Limiting the number of checkboxes selected by user - javascript

i have a page on there.i have number of check boxes.i want user to select on three not more than that and one check box has the value "NOT interested ",if user click on this all other check box must has to disabled.for that i tried javascript.
this is what i tried
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.form1.user[portal_choice].length; i++) {
if (document.form1.user[portal_choice][i].checked) {
total = total + 1;
}
if (total > 3) {
alert("Please Select only three")
document.form1.user[portal_choice][j].checked = false;
return false;
}
}
}
i getting error in the portal_choice variable.That is mapped with the database column name and user is my table name.
help me to do that and suggest me to disabling the checkbox when user click on "NOT INTERSTED".and its not rail 3.0
thanks pal for consideration.........

Using this syntax document.form1.user[portal_choice], you are telling Javascript that you want the form called 'form1' and from that form, get the elements called 'user', and look at the one with an index that is contained in the (javascript) variable 'portal_choice'. That variable is not defined in your function.
I am not familiar with Ruby, but from some quick reading, it looks like you can refer to Ruby variables directly in html, but not in Javascript. I think you have to wrap it with <%= %> like so:
document.form1.user[<%= portal_choice %>].length
However, I don't see why you would use a Ruby variable here. You just want to iterate through all of the checkboxes, right? I don't think checkbox elements are ever 2-dimensional arrays, as in
document.form1.user[portal_choice][i]
I think you really just want to do this:
function chkcontrol(j) {
var total = 0;
for (var i = 0; i < document.form1.user.length; i++) {
if (document.form1.user[i].checked) {
total = total + 1;
}
if (total > 3) {
alert("Please Select only three")
document.form1.user[j].checked = false;
return false;
}
}
}
Check this fiddle

Related

Set value/text to dropdown list

I am using the following jquery postcode lookup and I am trying to push values and hard code the process in javascript.
I am using the following to give the postcode textbox a valid postcode, and then forcing the button click to find the addresses.
document.getElementById("idpc_input").value = "LL17 0PN";
document.getElementById('idpc_button').click();
This so far works, after this a dropdownlist appears with the id of 'idpc_dropdown', I am trying to (in javascript or jquery) select an option
Here is what I have done but it does not work
var select = document.getElementById("idpc_dropdown");
document.getElementById("idpc_dropdown").text = '2 Elwy Cottages Heol Esgob';
And also:
var desiredValue = "2 Elwy Cottages Heol Esgob"
var el = document.getElementById("idpc_dropdown");
for(var i=0; i<el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.selectedIndex = i;
break;
}
}
UPDATE:
Let me explain the process and order, 1- Type in postcode and press the button to find my address 2- a dropdownlist then renders and appears .. I Think this is why it is not working for my desired dropdownlist as its not loaded when the page is loaded, it is when the button has been pressed
Provided that i is the same as the index of the item you wish to select, I'd set the dropdown's value attribute to that index:
let el = document.getElementById("idpc_dropdown");
for(let i = 1; i <= el.options.length; i++) {
if ( el.options[i].text == desiredValue ) {
el.value = i; // here
break;
}
}

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

How do I pass form elements to a javascript validation function?

I have a form that lists users, and for each user there is a drop down menu (2 choices: waiting, finished) and a comments textbox. The drop down menus are each labeled "status-userid" and the comments textbox is labeled "comments-userid" ... so for user 92, the fields in his row are labeled status-92 and comments-92.
I need to validate the form in the following way:
If the value of the status is "finished", I have to make sure that the user entered comments to correspond with that specific drop down menu.
So far, I have:
function validate_form () {
valid = true;
/*here's where i need to loop through all form elements */
if ( document.demerits.status-92.value == "finished" &&
document.demerits.comments-92.value == "")
{
alert ( "Comments are required!" );
valid = false;
}
return valid;
}
How do I loop through all of the status-userid elements in the form array?! Or is there another way to do this?
This should do it in raw Javascript (no framework).
var form = document.demerits;
for (var i = 1; i <= 100; i++)
{
if (form["status-" + i.toString()].value == "finished" &&
form["comments-" + i.toString()].value == "")
{
// enable visibility of element next to comments indicating validation problem
valid = false;
}
}
Using alerts would be bad though.
You'll need a collection of the dropdowns in your form. This can be acquired by using getElementsByTagName.
var dropdowns = document.demerits.getElementsByTagName("select");
for (var i = 0; i < dropdowns.length; i++)
{
// You can now reference the individual dropdown with dropdowns[i]
}

Categories