I am trying to create a validation for a list of radio buttons, which, if successful, prompts a confirm box. The confirm box must state which button the user has selected, and then allow them to confirm.
The validation works, but when the popup box appears, I can't get the user's selection to display in the message, either by using checked or checked.value. Here's the code:
var checked = null;
var inputs = document.getElementsByName('levels');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = inputs[i];
break;
}
}
if(checked==null)
{
alert('Please choose an exam level.');
return false;
}
else {
return confirm('You have chosen '+ checked + ', is this correct?');
}
Using this code, the message displayed is "You have chosen [object HTMLInputElement], is this correct?", regardless of which button is selected.
How do I correctly refer to the variable to avoid this?
You probably want checked = inputs[i].value. inputs[i] is the DOM Element, when cast to a string it becomes "[object HTMLInputElement]" (in case of an input element).
Related
I am using Snippets in the developer tools of a Chromium based web browser (Edge). I am trying to fill out a select box on a form from a website. The issue is that the select box options are dynamically created and are based on a selection from another select box. Every time the 'parent' selection is made the page refreshes and populates the new options for the second select box.
Here is a function that I used to set the first select box, however it doesn't work on the second one. I think it has something to do with when the page refreshes but I am not sure.
//Find value by entered text
function selectElement(selectorType, selector, text) {
var e = document.getElementById(selector);
//find value of text
for (var i = 0; i < e.options.length; i++) {
if (e.options[i].text === text) {
e.selectedIndex = i;
break;
}
}
if (selectorType == "id") {
jqSelector = '#'+selector;
$(jqSelector).val(e.value).change();
}
console.log(jqSelector, e.value);
}
selectElement('id', 'mySelector', "My Text");
For the code below it looks for an empty field in the 4 required fields if the user enters the address/city/state/zip field. Then it loops to check if any of them are empty. If all 4 are empty, then validation passes. If All of them contain data, then it should pass. The only time it should fail is if 1-3 of them are empty.
var validator = $("#AddressInfoForm").kendoValidator(
{
rules: {
PayeeRequired: function (input) {
if (input.is("[name=Address]") || input.is("[name=City]") || input.is("[name=State]") || input.is("[name=Zip]")) {
var fieldsBlank = 0;
var requiredFields = ["Address", "City", "State", "Zip"];
for (var i = 0; i < requiredFields.length; i++) {
var val = $('#' + requiredFields[i]);
if (val.val() == "") {
fieldsBlank += 1;
}
}
if (fieldsBlank > 0 && fieldsBlank < 4 && input.val() == "")
input.addClass("inputfields-validation-error");
fieldsBlank = 0;
return false;
}
input.removeClass("inputfields-validation-error");
return true;
}
}
},
}
).data("kendoValidator");
The issue I'm having with this is that...
The previous validation messages do not disappear. They only disappear once I click into each input box. It should be checking dynamically across the board since all 4 fields are linked. This means if 3 fields are empty except one, then there should be errors for those 3 fields. Once I clear the 4th field, then all of those errors should hide. Unfortunately it only hides for the last field that I input into and then I need to individually click into each field.
Working code expectant...
Overall I am looking for improve/correct my code so that
Show the error message for the blank fields when more than zero and less than 4 are blank.
Dynamically update so that when I clear all the fields, it clears all the error messages. When I fill one, then the other 3 blank fields display errors.
No errors when all 4 are filled.
edit--------
utilizing
$("#Address, #City, #State, #Zip").on("change", function () {
isModified = true;
validator.validate();
});
Seems to work how I want; however, validator.validate() sets off the validation errors for all the other fields in my form. I only want the validation set off for the 4 fields Address, City, State, and Zip. Any ideas?
$("#Address, #City, #State, #Zip").on("change", function () {
validator.validateInput($("input[name=Address]"));
validator.validateInput($("input[name=City]"));
validator.validateInput($("input[name=State]"));
validator.validateInput($("input[name=Zip]"));
});
Seems to work well. Let me know if there's a better way to do this!
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;
}
}
I have a few asp:Textbox elements in my code, which I was disabling with javascript after the user clicks validate.
eg:
<asp:TextBox CssClass="dateClass" ID="fromDateE" width="100px" runat="server" Text=""></asp:TextBox>
My javascript function was :
function disableDateFields()
{
var dates = document.getElementsByClassName("dateClass");
for (var i = 0; i < dates.length; i++)
{
//console.log(dates[i]);
dates[i].disabled = true;
}
}
The problem I had was after submit the value I had inside the textbox was getting cleared.
To get around this problem I changed the JS function so instead of disabling I set the readOnly property of the text box to true :
function disableDateFields()
{
var dates = document.getElementsByClassName("dateClass");
for (var i = 0; i < dates.length; i++)
{
//console.log(dates[i]);
dates[i].readOnly= true;
}
}
I am just wondering why disabling the textbox clears out the value inside of it? Is this simply the default behavior or am I missing something?
In this case ViewState has nothing to do with this. The problem lies in the fact that disabled input controls are not part of the Form Post back to the server. But because the TextBox does still exists on the page asp.net will fill it with the values it receives from PostBack, but that one is null so the TextBox is made empty.
You can check this with the following snippet. You will see that fromDateE.UniqueID does not exists and thus fromDateE will be emptied.
if (Request.Form[fromDateE.UniqueID] == null)
{
fromDateE.Text = "Form Post was empty.";
}
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]
}