I am trying to output the selected checked items from my list (I am using checkboxes) on the alert message on my page. Essentially, when the user hits the Delete button, I want a confirmation box to pop up and show the user which items they have selected to confirm it's correct (in this case, Serial Numbers). By default, all checkboxes are false (unchecked). If a checkbox is checked, the checkbox variable = true. Below is the function I wrote to do this:
function validateDeleteForm() {
var checkboxs=document.getElementsByName("pickSerial");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
}
}
if(okay)
{
if (confirm("Do you want to delete the selected Serial Number(s) from casting? Hit OK to Delete or CANCEL to re-select: " + this.checkboxs ) == true) { // this will delete selected serial numbers and display
return true;
}
//return true;
else { // this will cancel the delete dialogue and allow user to re-select
return false;
}
}
else {
alert("You have at least one line to be checked");
return false;
}
}
Does anyone see what I am doing wrong? I have tried referencing the checked items doing checkboxs[i].value, this.checkboxs[i], and calling the checkboxs variable but they all show as undefined.
Here is a screenshot of the output currently.
Thank you for any help.
Using querySelectorAll you can right away select all of the checked elements. There is no need to have to loop to find the check ones with this. You can then turn the html collection into an array to get all of the values. You can then use that array to display the info to the use.
const cbs = Array.from(document.querySelectorAll('[name="pickSerial"]:checked'));
const serials = cbs.map(function (cb) { return cb.value; });
if (serials.length) {
console.log(serials.join(",");
}
Adding to your solution, you can create an array to track checked items and then when printing, just use that array
Sample
const checked = [];
// When you are setting okay = true, push that value in checked
checked.push(checkboxs[i].value)
// Now when you are showing it in confirm box just join the array
confirm('text ' + checked.join(', '))
Hope that helps.
Related
I have a grid in which user can add as many rows as he wants and there are two textboxes (Minimum Value & Maximum Value). When the user enters Min and Max value. I am checking whether the range that user has entered is already there in the database. if yes then it shows me an alert. I am doing this on focusout Now the problem is that the alert keeps popping up infinite times when I click from one textbox directly to another textbox. Can anyone help me with this?
Here is the function on my focus out
function CheckValidation(obj) {
var ajx = new AJAXsupport();
ajx.resetVar();
ajx.addData('CL', 'CheckValidation');
var sucSave = function() {
if (ajx.getRefreshText() != "0") {
alert(ajx.getMessage());
$('#btnSave').attr('disabled', 'disabled');
return false;
} else {
$('#btnSave').attr('disabled', false);
}
}
customSave(ajx, sucSave);
}
}
So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code
I have a button that is created on each slide in a quiz game. Radio buttons containing the answer choices are appended from an object onto each slide as you cycle through the questions. I want to require that a radio button be clicked on before you can access the nextQuestion button. You can find the .append() on line 5 of the code below (inside of the loadQuestion function). What method would be the best way to achieve the desired result? If you need more of the code, let me know.
var loadQuestion = function (){
$('.question-name').html(name + (qnum) +"/"+ total);
$('.question').html(questions[count].question);
for(var i=0; i<questions[count].options.length; i++) {
$('.inputs').append('<input type="radio" name="question" value="'+questions[count].options[i]+'">'+questions[count].options[i]+'<br>')
}
};
/*--- First Question ---*/
var name = "Question ";
var qnum = 1;
var count = 0;
var total = questions.length;
loadQuestion();
/*--- When the Next Question Button is Hit ---*/
nextQuestion.click(function() {
$('.inputs').html("");
qnum++;
count++;
if (qnum <= 4) {
loadQuestion();
} else if (qnum == 6) {
$('.question-name').html("Your Score:");
$('.question').html("You got X out of 5 questions correct!");
nextQuestion.html("Home Screen").click(function() {
location.reload();
});
} else if (qnum == 5){
loadQuestion();
$('.next-question').html("Get Score!");
}
});
$(document).ready(function () {
$('#nextButton').attr('disabled', true);//disable the button by default on page load
$("input[type=checkbox]").on("click", function () {
if (this.length > 0) {
$('#nextButton').attr('disabled', false);//enable only when the checkbox is checked
}
});
});
I hope this helps!
Security note: Anybody can remove the disabled attribute from the button tag using developer tools in the browser. Use the backend to validate the checkbox value.
There's more than one way to go about this:
"Prevent button press until radio is selected"
From a ui/ux perspective your request raises the following question: "If the user isn't supposed to click on the button until the radio is selected, why is the button available for them to press before the radio is selected?" So, let's start there.
//pseudo-code - use delegate binding '.on()' for dynamically generated elements
$('.inputs').on('click', 'input[name="question"]', function({
if ($(this).is(':checked')) {
$('#nextButton').attr('disabled', false);
} else {
$('#nextButton').attr('disabled', true);
} /*... snip ...*/
}));
Or, you could generate the nextButton after an answer is selected much in the same way that you are currently generating the radio button - just remember to use delegate event binding. This is probably the "better way" because as has already been pointed out by #zadd, the disabled property can be circumvented.
Without reinventing the wheel, you could also just check to see if there's a radio selected when the button is pressed.
// pseudo-code again
nextQuestion.click(function() {
if($('input[name="question"]:checked').length > 0){
// checked!!! go do stuff!!!
} else {
// not checked! i should probably throw an alert or something...
alert('please answer the question before proceeding...');
}
});
Ok, I have a form with lots of different inputs, each has the same class name on it. What I need to do is loop though all of these inputs, which the user can add more to, with an AJAX call, making sure all inputs are four numbers only.
Now I can get it to check that it is of a length but when I try to add a check to make sure its a number, it does not seem to work, this is my current code:
var ValidMyData = function() {
$('#FORM-ID-HERE').on('submit',function(e) {
e.preventDefault();
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
$(Numbers).each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 ) {
return $(this).css("background-color","#FF0004");
} else {
return $(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
This works, if the inputs on my number field are not four in length, it makes the background color red, and then removes that background color if its then changed to be four.
I have tried some things but nothing as worked. I have mainly being playing with the IsNumeric() function, by adding that on my if check. Also, although this works, I don't think my return call is working right, I think I am doing something wrong but can not put my finger on it :). - When I console.log the CheckNumbers() inner function, I get undefined back.
All help most welcome.
Thanks
this code will check if it is 4 characters and if it's a number:
var ValidMyData = function() {
$('#FORM-ID-HERE').bind('submit',function(e) {
Numbers = $('.NumberClass');
//Check if job number is only 4 in length
function CheckNumbers() {
Numbers.each(function() {
var GetCurrentInput = $(this).val();
if( GetCurrentInput.length != 4 || !/([0-9])+/.test(String(GetCurrentInput))) {
return $(this).css("background-color","#FF0004");
e.preventDefault();
} else {
$(this).css("background-color","transparent");
} //End of if
}); //End of each
} //end of inner function
}); //end of on submit function
} //end of valid check function
ValidMyData();
EDIT
I updated the answer using your own code, which now will submit the form if all the inputs are filled correctly, else it highlights it and doesn't submit the form.
I have 8 check boxes, split into groups of 2. in the first group, I have one checkbox labeled checkbox1 and one labeled checkbox2. I want a JavaScript code that will allow me to be able to check on the form submit whether at least one of 2 of these checkboxes has been checked for each group.
I do not want a script that simply checks to see if you have checked only one checkbox as this will mean the user would not have to check at least one of the other checkboxes in the other group of checkboxes.
Does anyone know of a way of how I can do this please and am I going along the right lines?
$('#form_check').on('submit', function (e) {
if ($("input[id=box1]:checked").length === 0) {
if ($("input[id=box2]:checked").length === 1) {
} else {
if ($("input[id=box2]:checked").length === 0) {
if ($("input[id=box1]:checked").length === 1) {
e.preventDefault();
alert('no way you submit it without checking a box');
return false;
}
}
}
}
});
Do it like this:
$("button").click(function(){
var length = 0; // initial length
$(".group").each(function(){
// if box is checked, add 1, else 0
length += ($(this).find("input:checked").length === 1);
});
// if there are as many box's checked as many groups, i.e. one checked box per group
if(length === $(".group").length){
alert("y");
}else{
alert("no");
}
});
DEMO