I have a form with three sections for variables: the first section is a text field that requires the user to enter a number lets call this user_number; next, is a set of radio buttons. three of them, that determine the 'type' variable of the output. we shall call this banner_type. finally, there is another set of radio buttons, this time, sixteen of them. these determine the 'style' variable of the output, and we can name it banner_style.
To get the script going, there is a button named Generate. it is NOT a submit button. finally, the output area is a div which will show the right results.
Now, the purpose of this form is to allow a user to choose a certain type of image, one that can change in type and style, and output different information for different users, hence the three variables.
If it helps, this is supposed to be simplify the selection of a Folding#Home sig banner. the coding is as follows:
<form>
User Number: <input type="text" id="user_number" /><br /><br />
Team & User Info: <input type="radio" name="banner_type" value="type0" /><br /><br />
Team Info Only: <input type="radio" name="banner_type" value="type1" /><br /><br />
User Info Only: <input type="radio" name="banner_type" value="type2" /><br /><br />
1: <input type="radio" name="banner_style" value="1" /><br /><br />
2: <input type="radio" name="banner_style" value="2" /><br /><br />
3: <input type="radio" name="banner_style" value="3" /><br /><br />
4: <input type="radio" name="banner_style" value="4" /><br /><br />
5: <input type="radio" name="banner_style" value="5" /><br /><br />
6: <input type="radio" name="banner_style" value="6" /><br /><br />
7: <input type="radio" name="banner_style" value="7" /><br /><br />
8: <input type="radio" name="banner_style" value="8" /><br /><br />
9: <input type="radio" name="banner_style" value="9" /><br /><br />
10: <input type="radio" name="banner_style" value="10" /><br /><br />
11: <input type="radio" name="banner_style" value="11" /><br /><br />
12: <input type="radio" name="banner_style" value="12" /><br /><br />
13: <input type="radio" name="banner_style" value="13" /><br /><br />
14: <input type="radio" name="banner_style" value="14" /><br /><br />
15: <input type="radio" name="banner_style" value="15" /><br /><br />
16: <input type="radio" name="banner_style" value="16" /><br /><br />
<input type="button" id="Generate" value="Generate" />
</form>
Image URL: <div id="URL" style=display:inline;></div>
<script type="text/javascript">
document.getElementById('Generate').addEventListener('click',function() {
*SOMETHING NEEDS TO GO HERE*
document.getElementById('URL').innerHTML = 'http://folding.extremeoverclocking.com/sigs/sigimage.php?u=' + user_number + banner_style + banner_type;
});
</script>
So my end goal is to have the basic image address, as shown at the end of the script, then the user number, which should be an exact copy of whatever the user inputs in the text field, then the banner style, which will look something like this:
&c1=000000&c2=000000&c3=000000&c4=000000&c5=000000
This will be different for each different banner_style. Each value represents a hex colour code for different elements on the image itself. Finally, the banner type, which will look something like this:
&bg=0
This will either be 0, 1, or 2.
At this point, i should make it clear that i hardly ever use javascript, so ill need everything explained to me clearly, so i can also learn from it. Also, if at all possible, id like this to be pure JS... none of that jQuery stuff, or similar.
Sheesh, no jQuery?
Let me give you the jQuery version first since its far easier.
// load when page is done loading
$(function(){
// jQuery is just like CSS in that you use selectors to target a node element
$("#Generate").on("click", function(){
// get form values for each style we need
var user = $('#user_number').val();
var style = $('form input[name=banner_type]:checked').val();
var type = $('form input[name=banner_style]:checked').val();
// set image variable by concatenating the values together
var image = "http://folding.extremeoverclocking.com/sigs/sigimage.php?u=" + user + style + type;
// insert image path using the image variable set above into element with id of "URL"
$("#URL").html( image );
});
}); // close jquery on page load
Now in plain JavaScript... here goes.
// have to iterate each group to obtain the value
// function has borrowed from http://www.somacon.com/p143.php/
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
var user = document.getElementById('user_number').value;
var style = getCheckedValue('banner_style');
var type = getCheckedValue('banner_type');
// set image variable
var image = "http://folding.extremeoverclocking.com/sigs/sigimage.php?u=" + user + style + type;
// insert image into element node with ID of "URL"
document.getElementById("URL").innerHTML = image;
Related
I am able to check for all radio buttons that are selected.
However ,I only want to check for those that are rendered (the ones that don't have "display:none").
So if only the 1 and 3 division is selected, it should display true. Currently, it will only display true if all 3 is selected.
EDIT
: I have taken Shree33 answer and made it work with input:radio:visible.
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
var all_answered = true;
$(".division input:radio:visible").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
alert(all_answered);
})
});
.test{
//display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />
</div>
<div class="division test">2
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />
</div>
<div class="division">3
<input type="radio" name="radio3" value="false" />
<input type="radio" name="radio3" value="true" />
</div>
<div>4
<input type="radio" name="radio4" value="false" />
<input type="radio" name="radio4" value="true" />
</div>
</form>
click
Just use a selector that excludes the non-displayed ones and compare the amount of found elements to the amount of checked radio buttons in that same set (using JQuery context). If the amounts are the same, all visible buttons have been selected.
Also, you really shouldn't use a link when you aren't actually navigating anywhere. If you just need to trigger some code (as is the case here), just about any element can have a click event handler bound to it. By not using an a, you don't have to cancel the native behavior of the link (evt.preventDefault()) and those that rely on assistive technologies, like screen readers won't have problems that occur when the screen reader encounters a link that doesn't actually navigate.
$(function() {
$("#click").click(function(e) {
// Get only the visible DIVs that have the "division" class
var visibleDIVs = $("div.division:not(.hide)");
// Now that we have a collection that contains only the div elements
// that are visible, we can get the count of them easily with: visibleDIVs.length
// We can also search the document for any checked radio buttons, but only those
// that are part of the visible divs collection like this: $("input:radio:checked", visibleDIVs).
// (the second argument (, visibleDIVs) constrains the search for radio buttons to just
// the collection of visilbe divs we've already gotten) and once we have those,
// we can also get the count of them by checking the .length of that collection.
// If the count of visible divs (visibleDIVs.length) equals the count of the visible
// checked radio buttons, then all buttons have been checked:
if(visibleDIVs.length === $("input:radio:checked", visibleDIVs).length){
alert("All Answered");
}
})
});
/* Make the clickable div look like a link */
#click {
text-decoration:underline;
cursor:pointer;
}
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false">
<input type="radio" name="radio1" value="true">
</div>
<div class="division hide">2
<input type="radio" name="radio2" value="false">
<input type="radio" name="radio2" value="true">
</div>
<div class="division">3
<input type="radio" name="radio3" value="false">
<input type="radio" name="radio3" value="true">
</div>
</form>
<div id="click">click</div>
You were close, just change the $("input:radio") selector to $("input:radio:visible"). That should work.
$(document).ready(function() {
$("a").click(function(e) {
e.preventDefault();
var all_answered = true;
$("input:radio:visible").each(function() {
var name = $(this).attr("name");
if ($("input:radio[name=" + name + "]:checked").length == 0) {
all_answered = false;
}
});
alert(all_answered);
})
});
.test{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="division">1
<input type="radio" name="radio1" value="false" />
<input type="radio" name="radio1" value="true" />
</div>
<div class="division test">2
<input type="radio" name="radio2" value="false" />
<input type="radio" name="radio2" value="true" />
</div>
<div class="division">3
<input type="radio" name="radio3" value="false" />
<input type="radio" name="radio3" value="true" />
</div>
</form>
click
Where you're getting the length,
if ($("input:radio[name=" + name + "]:checked").length == 0) {
try
if ($("input:radio[name=" + name + "]:checked").length == 0 && $(this).is(":visible") {
Is that what you are looking for? Also do you need to get the name and concat it, as won't $(this) get you your object as well?
You can check for the parent visible state too:
if (($("input:radio[name=" + name + "]:first").parent().is(':visible')) &&
($("input:radio[name=" + name + "]:checked").length == 0)) {
all_answered = false;
}
https://jsfiddle.net/StepBaro/bLp8wbnh/3/
Pls have a look at this. Seems to solve your "if visible" issue with window.getComputedStyle.
Example code:
Present <input type='checkbox' value='student1' id='id_A' name='A' />
Absent <input type='checkbox' value='student1' id='id_B' name='B' />
Comments <input type='text' name='comments' id='id_comments' />
Present <input type='checkbox' value='student2' id='id_A' name='A' />
Absent <input type='checkbox' value='student2' id='id_B' name='B' />
Comments <input type='text' name='comments' id='id_comments' />
and so on in a loop for all users, comments field having text is optional.
Issue:
I would like depending lets say for student1, if the checkbox field has text, I want to associate the appropriate checkbox value that is checked, in this case if student1 is present and has text in comments, 'always 10 minutes late'. I should be able to have probably in a array,
PresentArray = {'Student1' : 'always 10 minutes late', 'Student2' : ''}
I am new to programming, I prefer to use checkboxes for specific reasons with the users.
I should be able to have probably in a array, 'PresentArray =
{'Student1' : 'always 10 minutes late', 'Student2' : ''}'
Your PersentArray is not an array [] but object {}.
Keeping your HTML inputs this way is a mistake. You have duplicate id attributes which should be unique within document.
Also you did not include any code, have you tried anything? Stackoverflow is a place to learn, we are not here to do a homework for you.
I've refactored your HTML. If I understood you correctly you need to check if student is present and has given comment then we can add him to an array. This is what the script does.
Instead of checkbox we use radio because student can't be present and absent at the same time.
See working example and read my comments carefully to have better understanding. If you have any question be sure to ask.
var students = [];
var formInputs = document.querySelectorAll('input');
// You can use this function eg. var studentsInfo = populatePresentArray();
// Function returns populated PresentArray []
function populatePresentArray() {
for (i = 0; i < formInputs.length; i++) {
var input = formInputs[i];
// if input is type radio and is checked then we assume
if (input.value === 'present' && input.checked) {
// query Comment input for current student
var comment = document.querySelector('input[name="' + input.name + '-comments"]');
// Now let's check if comments has required text
if (comment.value === 'always 10 minutes late') {
// All conditions are met, lets add to array new record
students.push({ [input.name] : comment.value });
}
}
}
// Log it
console.log(students);
return students;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="studentsForm">
Present <input type="radio" value="present" name="student1" checked />
Absent <input type="radio" value="absent" name="student1" />
Comments <input type="text" name='student1-comments' value="" />
<br>
Present <input type="radio" value="present" name="student2" checked />
Absent <input type="radio" value="absent" name="student2" />
Comments <input type="text" name='student2-comments' value="always 10 minutes late" />
<br>
Present <input type="radio" value="present" name="student3" checked />
Absent <input type="radio" value="absent" name="student3" />
Comments <input type="text" name='student3-comments' value="always 10 minutes late" />
<br>
Present <input type="radio" value="present" name="student4" />
Absent <input type="radio" value="absent" name="student4" checked />
Comments <input type="text" name='student4-comments' value="always 10 minutes late" />
<br>
Present <input type="radio" value="present" name="student5" checked />
Absent <input type="radio" value="absent" name="student5" />
Comments <input type="text" name='student5-comments' value="" />
<br>
<button onclick="populatePresentArray()" type="button">PresentArray</button>
</form>
How do I check multiple variable inputs at once to ensure that the regex is working? Everytime I enter anything, the form submits and doesn't alert anything.
I have tried test()method of regex validation too, and still no luck.
I am trying to validate user input with the following regex that makes to where anything that is not a number or blank space is considered a wrong input.
var format=/^(\s*|\d+)$/;
It only accepts numbers and blank spaces in the text box.
The following javascript is what I have:
var pitch = document.getElementById("pitch");
var chisel = document.getElementById("chis");
var saw = document.getElementById("saw");
//var arguments = [chisel, saw, pitch];
var format = /^(\s*|\d+)$/;
function regexTest() {
if (!chisel.match(format) && !saw.match(format) && !pitch.match(format)) {
alert("Repressed Action");
return false;
} else {
alert('Thank you');
}
}
<div class="lab">
<form method="post" action="http://weblab.kennesaw.edu/formtest.php">
Chisels: <input type="text" name="chisels" id="chis" size="5" /> Saw: <input type="text" name="saw" id="saw" size="5" /> Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5" />
<br /> Customer Name: <input type="text" name="customer name" size="25" />
<br /> Shipping Address: <input type="text" name="shipping address" size="25" />
<br /> State:
<input type="radio" id="master" name="card" value="master" /><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american" /><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa" /><label for="visa">Visa</label>
<br />
<input type="reset" value="Reset" />
<div class="lab">
<button onclick="regexTest()">Submit</button>
<button onclick="return false">Cancel</button>
</div>
There are a number of issues with your code, below I've refactored it to be a bit easier to read and so it works.
The validation listener should be on the form's submit handler, not the submit button since forms can be submitted without clicking the button. Also, if you pass a reference to the form to the listener, it's much easier to access the form controls by name.
You should get the values of the form controls when the submit occurs, not before. Your code gets the values immediately, before the user has done anything (and possibly before the form even exists), so put that code inside the listener function.
Lastly, the regular expression needs to match anything that isn't a space or digit, so:
/[^\s\d]/
seems appropriate. However, this will still allow the form to submit if the fields are empty (they don't contain non-digits or non-spaces). You'll need to add a test for that.
function regexTest(form) {
// Get values when the function is called, not before
var pitch = form.pitchfork.value;
var chisel = form.chisels.value;
var saw = form.saw.value;
// Test for anything that's not a space or digit
// var format = /^(\s*|\d+)$/;
var format = /[^\s\d]/;
if (format.test(chisel) || format.test(pitch) || format.test(saw)) {
// There must be at least one non-space or non-digit in a field
alert("Repressed Action");
return false;
} else {
alert('Thank you');
// return false anyway for testing
return false;
}
}
<div class="lab">
<form onsubmit="return regexTest(this)">
Chisels: <input type="text" name="chisels" id="chis" size="5"><br>
Saw: <input type="text" name="saw" id="saw" size="5"><br>
Pitchfork: <input type="text" name="pitchfork" id="pitch" size="5"><br>
Customer Name: <input type="text" name="customer name" size="25"><br>
Shipping Address: <input type="text" name="shipping address" size="25">
<br> State:
<select name="states">
<option>Florida</option>
<option>Georgia</option>
<option>Alabama</option>
</select>
<br>
<input type="radio" id="master" name="card" value="master"><label for="master">MasterCard</label>
<input type="radio" id="american" name="card" value="american"><label for="american">American Express</label>
<input type="radio" id="visa" name="card" value="visa"><label for="visa">Visa</label>
<br>
<input type="reset" value="Reset">
<div class="lab">
<button>Submit</button>
<button onclick="return false">Cancel</button>
</div>
Hopefully this gets you to the next step.
JS :
function checkValue(option) {
if (option == "4") {
alert("Correct");
var pop = parseInt(window.name++);
alert(pop);
window.location="q2.html";
}
else {
alert("False, Option (4) is the Correct Answer.");
window.location="q2.html";
}
}
Html :
<html>
<input type="radio" name="option_1" value="1" onclick="checkValue(this.value);" /> Hyper Text Markup Languages <br /> <br />
<input type="radio" name="option_2" value="2" onclick="checkValue(this.value);" /> Highest Text Markup Language <br /> <br />
<input type="radio" name="option_3" value="3" onclick="checkValue(this.value);" /> Hyper Total Markup Language <br /> <br />
<input type="radio" name="option_4" value="4" onclick="checkValue(this.value);" /> Hyper Text Markup Language <br /> <br />
</html>
First thing, I'd clean up the HTML code a bit... I assume the four radio buttons are all possible answers to one question, in which case they should all have the same name (not value) so that you can only choose one answer; then in the script I'd would need to use more information than just the value of the checked answer, so instead of sending this.value to the function, I'd just send this:
<input type="radio" name="question_1" value="option_1" onclick="checkValue(this);" /> Hyper Text Markup Languages <br /> <br />
<input type="radio" name="question_1" value="option_2" onclick="checkValue(this);" /> Highest Text Markup Language <br /> <br />
<input type="radio" name="question_1" value="option_3" onclick="checkValue(this);" /> Hyper Total Markup Language <br /> <br />
<input type="radio" name="question_1" value="option_4" onclick="checkValue(this);" /> Hyper Text Markup Language <br /> <br />
In the script, to disable the radio buttons after they've been clicked, I would add a function that goes through each radio button that has the same name (as mentioned above) as the one that's been clicked, and disable it:
var radiobuttons = document.getElementsByName(option.name);
for(i = 0; i < radiobuttons.length; i++) {
radiobuttons[i].disabled = true;
}
Then, of course, the alert to let the visitor know whether they've got the right answer:
if (option.value == "option_4") {
alert("Correct");
} else {
alert("False, Option (4) is the Correct Answer.");
}
Here's a fiddle: http://jsfiddle.net/Niffler/nyqk6gga/
(I'm assuming you don't want to use jQuery; otherwise there would be much nicer-looking ways to do this...)
$(document).delegate(".rndmyradio","click",function () {
$(this).hide();
//if you want values of selected
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="rndmyradio" type="radio" name="option_1" value="1" /> <label>Hyper Text Markup Languages </label><br /> <br />
2. <input class="rndmyradio" type="radio" name="option_2" value="2" /> Highest Text Markup Language <br /> <br />
3. <input class="rndmyradio" type="radio" name="option_3" value="3" /> Hyper Total Markup Language <br /> <br />
4. <input class="rndmyradio" type="radio" name="option_4" value="4" /> Hyper Text Markup Language <br /> <br />
Well I am trying to build a web page that has set of radio buttons. I am using jquery to check if all the radio buttons are checked or not. Here is the code:
<body>
<p class="Cal">Welcome,</p>
<hr />
<p class="Radio1">Answer the questions below. You will find the results after clicking 'Check my score'.</p>
<hr />
<form method="post">
<p class="Question">1. Do you sleep early at night? (Anywhere around 9-10pm)</p>
<p>
<label>
<span class="Radio">
<input type="radio" name="RadioGroup1" value="Yes" id="RadioGroup1_0" />
</span></label>
<span class="Radio"> Yes
<br />
<label>
<input type="radio" name="RadioGroup1" value="No" id="RadioGroup1_1" />
No
</label>
<br />
<label>
<input type="radio" name="RadioGroup1" value="Sometimes" id="RadioGroup1_2" />
Sometimes </label>
</span><br />
</p>
<p class="Question">2. Do you wake up early in morning?(Anywhere around 5-7am)</p>
<p>
<label>
<span class="Radio">
<input type="radio" name="RadioGroup2" value="Yes" id="RadioGroup2_0" />
Yes </span></label>
<span class="Radio"><br />
<label>
<input type="radio" name="RadioGroup2" value="No" id="RadioGroup2_1" />
No
</label>
<br />
<label>
<input type="radio" name="RadioGroup2" value="Sometimes" id="RadioGroup2_2" />
Sometimes
</label>
</span><br />
</p><input type="submit" value="Check my score" /></form></body>
Well there are 30 such questions. And my jquery code is as follows:
$(document).on('submit', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.Radio').each(function () {
// Question text
var Question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(Question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
else{
msg = "Done!";
alert(msg);
}
return validate;
});
Now I tried all ways possible to make this work. But even after I check radio button for each answer I keep on getting the popup saying "Please answer the following questions:" and then a blank list. I never get the message "Done!" even though answer for all the questions are checked.
Where is the fault?
You can use the HTML5 required attribute, which is better option.
You can also use JavaScript loop and retrieve the value from each radio group, using
$("input:radio[name=radiogroupX]:checked")