I'm currently building an order form but it seems that the method I am testing to loop through the check-boxes to see if a value is ticked or not isn't working. What am I doing wrong? In logic it seems all right - I would appreciate any help. Thanks in advance :-)
<script>
function order()
{
for(i=1;i<=7;i++)
{
alert(document.orderForm.order[i].checked);
}
}
</script>
<form name='orderForm'>
<p>Basic choices:</p>
<p>
<input type='checkbox' id='order1' name='order1' value='90' />
<label for="1"> Nano 1GB (£90)</label>
<br>
<input type='checkbox' id='order2' name='order2' value='155' />
<label for="2"> Nano 4GB (£155)</label>
<br>
<input type='checkbox' id='order3' name='order3' value='200' />
<label for="3"> Video 30GB (£200)</label>
<br>
<input type='checkbox' id='order4' name='order4' value='275' />
<label for="4"> Video 60GB (£275)</label>
</p>
<p>Options:</p>
<p>
<input type='checkbox' id='order5' name='order5' value='90' />
<label for="5"> Engraving (£10)</label>
<br>
<input type='checkbox' id='order6' name='order6' value='15' />
<label for="6"> Carrying case (£15)</label>
<br>
<input type='checkbox' id='order7' name='order7' value='18' />
<label for="7"> Car power adapter (£18)</label>
</p>
<p>
<input type="button" onClick="order();">
</p>
<p>Order Total</p>
<p>
<input type="text" name="orderTotal" id="orderTotal">
</p>
<p>VAT</p>
<p>
<input type="text" name="vat" id="vat">
</p>
<p>Order Total (+VAT)</p>
<p>
<input type="text" name="orderTotal_vat" id="orderTotal_vat">
</p>
</form>
document.orderForm.order is not an array. In fact, it doesn't exist. You need to build your id like this:
function order() {
for(i=1;i<=7;i++) {
alert(document.orderForm["order" + i].checked);
}
}
Here's a working fiddle.
Your current function implementation doesnt seem to be right.. well with the solution that you have here is how your funnction should look like:
<script>
function order()
{
for(i=1;i<=7;i++)
{
alert(document.getElementById("order"+i).checked);
}
}
</script>
or you can fix your names and then get it work. The array that you are trying to work with is constructed of a name that is shared across the checkboxes.
<script>
function order()
{
with(document.orderForm)
{
for(var i = 0; i < orderName.length; i++){
alert(orderName[i].checked);
}
}
}
</script>
<form name='orderForm'>
<p>Basic choices:</p>
<p>
<input type='checkbox' id='order1' name='orderName' value='90' />
<label for="1"> Nano 1GB (£90)</label>
<br>
<input type='checkbox' id='order2' name='orderName' value='155' />
<label for="2"> Nano 4GB (£155)</label>
<br>
<input type='checkbox' id='order3' name='orderName' value='200' />
<label for="3"> Video 30GB (£200)</label>
<br>
<input type='checkbox' id='order4' name='orderName' value='275' />
<label for="4"> Video 60GB (£275)</label>
</p>
<p>Options:</p>
<p>
<input type='checkbox' id='order5' name='orderName' value='90' />
<label for="5"> Engraving (£10)</label>
<br>
<input type='checkbox' id='order6' name='orderName' value='15' />
<label for="6"> Carrying case (£15)</label>
<br>
<input type='checkbox' id='order7' name='orderName' value='18' />
<label for="7"> Car power adapter (£18)</label>
</p>
<p>
<input type="button" onClick="order();">
</p>
<p>Order Total</p>
<p>
<input type="text" name="orderTotal" id="orderTotal">
</p>
<p>VAT</p>
<p>
<input type="text" name="vat" id="vat">
</p>
<p>Order Total (+VAT)</p>
<p>
<input type="text" name="orderTotal_vat" id="orderTotal_vat">
</p>
</form>
Fiddle: http://jsfiddle.net/P7CKG/
Without using with if you think that is confusing you:
<script>
function order()
{
for(var i = 0; i < document.orderForm.orderName.length; i++){
alert(document.orderForm.orderName[i].checked);
}
}
</script>
Your function is failing because the form elements are not named order[1], order[2], etc: they are named order1, order2. Thus, the code document.orderForm.order[i] references nothing.
Also, you should avoid accessing the form through the document.formName mechanism - get the element by ID instead. Likewise, rather than form.elementName, use form.elements[elementName] instead. These are, in my experience, more consistent between user agents.
function order () {
var frm = document.getElementById('orderForm');
for(i=1;i<=7;i++) {
alert(frm.elements['order'+i].checked);
}
return false;
}
function order(){
var arrChks = document.orderForm.getElementsByTagName('input');
for(i=0;i<arrChks.length;i++){
if(arrChks[i].type=='checkbox'){
alert(arrChks[i].checked);
}
}
}
but i reccomend you to use jquery or another javascript framework!
Complete example!
http://jsbin.com/amesek/
Zolved!
Related
I am relatively new to jQuery. I am trying to create a survey; in the survey each question in in its own div and is revealed by clicking the "Next" button. I just have all divs hidden except for the current div. I'm trying to write the answers to an object as I go to simplify the code. There are questions answered with radio buttons, some text areas, some check boxes, and some selects. Here is my code:
$('.next-button').click(function() {
if ($(this).parent().has('.survey-question-option')) {
replies[$(this).parent().attr('id')] = $(this).parent().contents('.survey-question-option:checked').val();
} else if ($(this).parent().has("textarea")) {
replies[$(this).parent().attr('id')] = $(this).parent().contents("textarea").val();
}
console.log(replies);
$(this).parent().attr('hidden', '');
$(this).parent().next().removeAttr('hidden');
});
I'm logging the Object (replies) to make sure things are working. As the code is currently formulated I get the answers to the first two questions (both of which are radio buttons) added to replies, but the next two objects (textareas) populate as undefined. ({reason: "bill", wish: "newstart", dislike: undefined, like: undefined}). I tried formulating the if statement as two separate statements:
if ($(this).parent().has('.survey-question-option')) {
replies[$(this).parent().attr('id')] = $(this).parent().contents('.survey-question-option:checked').val();
};
if ($(this).parent().has("textarea")) {
replies[$(this).parent().attr('id')] = $(this).parent().contents("textarea").val();
};
That returns undefined for the radio buttons, but the contents of the two textareas shows up in the object. ({reason: undefined, wish: undefined, dislike: "dislike text", like: "like text"}). In doing some testing on my own I've determined that if the if statement is formulates as if...else if the formula always applies the if statement only, but if it is created with two if statements it skips thew first and goes straight for the second.
My logic is that each Next button is in a div with the responses, so I should be able to look at the parent of the Next button, find the appropriate class, and get the value. And it seems to only work 50% of the time no matter how I formulate it.
EDIT: I am attaching the relevant html sections.
$('.next-button').click(function() {
if ($(this).parent().has('.survey-question-option')) {
replies[$(this).parent().attr('id')] = $(this).parent().contents('.survey-question-option:checked').val();
} else if ($(this).parent().has("textarea")) {
replies[$(this).parent().attr('id')] = $(this).parent().contents("textarea").val();
}
console.log(replies);
$(this).parent().attr('hidden', '');
$(this).parent().next().removeAttr('hidden');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="survey">
<div id="reason" class='radio'>
<p class="survey-question">What is the primary reason you visit the site? </p>
<input type="radio" id="bill" name="reason" class="survey-question-option" value="bill">
<label for="bill" class="survey-question-option-label">To view or pay my bill online</label><br>
<input type="radio" id="outage" name="reason" class="survey-question-option" value="outage">
<label for="outage" class="survey-question-option-label">To view or report an outage</label><br>
<input type="radio" id="start" name="reason" class="survey-question-option" value="start">
<label for="start" class="survey-question-option-label">To get information about starting or stopping services</label><br>
<input type="radio" id="hours" name="reason" class="survey-question-option" value="hours">
<label for="hours" class="survey-question-option-label">To find Frederick Waster's business hours</label><br>
<input type="radio" id="board" name="reason" class="survey-question-option" value="board">
<label for="board" class="survey-question-option-label">To get information about Frederick Water's governance or board meetings</label><br>
<input type="radio" id="devel" name="reason" class="survey-question-option" value="devel">
<label for="devel" class="survey-question-option-label">To get information about new water or wastewater lines for new development</label><br>
<input type="radio" id="other" name="reason" class="survey-question-option" value="other">
<label for="other" class="survey-question-option-label">Other</label><br>
<div id="other-fill-reason" class="other-fill" hidden>
<label for="othertext-reason" class="survey-question-option-label">Please specify: </label>
<input type="text" class="survey-question-other" id="othertext-reason">
</div>
<input type="button" class="next-button" id="reason-next" value="Next">
</div>
<div id="wish" class='radio' hidden>
<p class="survey-question">What do you wish the site did better?</p>
<input type="radio" id="newstart" name="wish" class="survey-question-option" value="newstart">
<label for="newstart" class="survey-question-option-label">Allow me to pay deposit while starting new service</label><br>
<input type="radio" id="outinfo" name="wish" class="survey-question-option" value="outinfo">
<label for="outinfo" class="survey-question-option-label">Provide easier-to-find information about outages</label><br>
<input type="radio" id="startstop" name="wish" class="survey-question-option" value="startstop">
<label for="startstop" class="survey-question-option-label">Make it easier to start and stop services</label><br>
<input type="radio" id="request" name="wish" class="survey-question-option" value="request">
<label for="request" class="survey-question-option-label">Make it easier to request maintenance for existing service</label><br>
<input type="radio" id="chat" name="wish" class="survey-question-option" value="chat">
<label for="chat" class="survey-question-option-label">Let me talk to customer service online</label><br>
<input type="radio" id="other2" name="wish" class="survey-question-option" value="other">
<label for="other2" class="survey-question-option-label">Other</label><br>
<div id="other-fill-wish" class="other-fill" hidden>
<label for="othertext-wish" class="survey-question-option-label">Please specify: </label>
<input type="text" class="survey-question-other" id="othertext-wish">
</div>
<input type="button" class="next-button" id="wish-next" value="Next">
</div>
<div id="dislike" class="textbox" hidden>
<p class="survey-question">What do you dislike about the site?</p>
<textarea id="dislike-text" class="like-dislike" cols="100" rows="5" maxlength="500" wrap="soft"></textarea><br>
<input type="button" class="next-button" id="dislike-next" value="Next">
</div>
<div id="like" class="textbox" hidden>
<p class="survey-question">What do you like about the site?</p>
<textarea id="like-text" class="like-dislike" cols="100" rows="5" maxlength="500" wrap="soft"></textarea><br>
<input type="button" class="next-button" id="like-next" value="Next">
</div>
has() doesn't return a boolean, it returns a jQuery object. Objects are always truthy.
If you want to test whether a selector finds anything, test the length of the result.
$('.next-button').click(function() {
if ($(this).parent().find('.survey-question-option').length > 0) {
replies[$(this).parent().attr('id')] = $(this).parent().find('.survey-question-option:checked').val();
} else if ($(this).parent().find("textarea").length > 0) {
replies[$(this).parent().attr('id')] = $(this).parent().find("textarea").val();
}
console.log(replies);
$(this).parent().attr('hidden', '');
$(this).parent().next().removeAttr('hidden');
});
So i can save one question but when i add more it doesnt work. I though i could just add on to postquestion function copy and paste and just change 16 to 15 but i guess that is to easy
I need to save about 16 total questions with 4 choices each question, and the selected radio is the correct answer.
Also is there a way to save selected radio buttons into session and local storage?
function postQuestion() {
var obj = {
question: document.getElementById("question16").value,
choice62: document.getElementById("choice62").value,
choice63: document.getElementById("choice63").value,
choice64: document.getElementById("choice64").value,
choice65: document.getElementById("choice65").value
}
try {
sessionStorage.setItem("data", JSON.stringify(obj));
} catch (error) {
alert("Enable Session storage");
}
return false;
}
function PreviewImage16() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage16").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview16").src = oFREvent.target.result;
sessionStorage.setItem("image", oFREvent.target.result);
};
};
<div>
Enter Question 16:
<input type="text" id="question16" name="question16">
<br>
<br> Next, add a correct answer and several incorrect answers for your question.
<br>
<form onsubmit="return postQuestion()">
<p>
<input type="radio" name="choice62" value="62">
<label>
<input id="choice62" size="50">
</label>
</p>
<p>
<input type="radio" name="choice63" value="63">
<label>
<input id="choice63" size="50">
</label>
</p>
<p>
<input type="radio" name="choice64" value="64">
<label>
<input id="choice64" size="50">
</label>
</p>
<p>
<input type="radio" name="choice65" value="65">
<label>
<input id="choice65" size="50">
</label>
</p>
<p>
<button type="submit"> Submit</button>
</p>
<br>
<img id="uploadPreview16" style="width: 100px; height: 100px;" />
<input id="uploadImage16" type="file" name="myPhoto16" onchange="PreviewImage16();" />
</div>
i have a complex div with input field somewhat like this
<input type="text" name="firstname">
<input type="text" name="lastname">
<input type="text" name="email">
<input type="text" name="address">
<div id="section_toClone">
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
</div>
<button id="add_more"> Add </button>
now when someone click on add i want something like this to happen
<input type="text" name="tree[tree1][fruit]">
<input type="text" name="tree[tree1][height]">
<input type="checkbox name tree[tree1][color] value="green">Green </input>
<input type="checkbox name tree[tree1][color] value="yellow">yellow </input>
<input type="text" name="tree[tree2][fruit]">
<input type="text" name="tree[tree2][height]">
<input type="checkbox name tree[tree2][color] value="green">Green </input>
<input type="checkbox name tree[tree2][color] value="yellow">yellow </input>
<input type="text" name="tree[tree3][fruit]">
<input type="text" name="tree[tree3][height]">
<input type="checkbox name tree[tree3][color] value="green">Green </input>
<input type="checkbox name tree[tree3][color] value="yellow">yellow </input>
and so on..... but my script only clone doesnt change the value of tree from tree1 to tree2 to tree3 and so on.... here is my jquery script
$('#add_more').click(function(){
$("#section_toClone").clone(true).insertBefore("#add_more").find('input').val("").val('');
});
how do i increment that automatically?? i want to mention one more thing in actual html code. it has more then 3 input and 3 checkbox field
Don't even bother putting the numbers into the array keys. Just let PHP take care of it itself:
<input name="tree[fruit][]" value="foo" />
<input name="tree[fruit][]" value="bar" />
<input name="tree[fruit][]" value="baz" />
Any [] set which DOESN'T have an explicitly specified key will have one generated/assigned by PHP, and you'll end up with
$_POST['tree'] = array(
0 => 'foo',
1 => 'bar',
2 => 'baz'
);
As long as your form is generated consistently, browsers will submit the fields in the same order they appear in the HTML, so something like this will work:
<p>#1</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][]" value="large" />
<p>#2</p>
<input name="foo[color][]" value="puce" />
<input namke="foo[size][]" value="minuscule" />
and produce:
$_POST['color'] = array('red', 'puce');
| |
$_POST['size'] = array('large', 'minuscule');
But if you start mixing the order of the fields:
<p>#3</p>
<input name="foo[color][]" value="red"/>
<input name="foo[size][] value="large" />
<p>#4</p>
<input namke="foo[size][] value="minuscule" />
<input name="foo[color][] value="puce" />
$_POST['color'] = array('red', 'puce');
/
/
$_POST['size'] = array('minuscule', 'large');
Note how they're reversed.
I wouldn't post this without feeling a bit ashamed of how bad it is written, but the following solution does the trick. Badly.
var treeCount = 1;
$('#add_more').click(function(){
$("#section_toClone")
.clone(true)
.insertBefore("#add_more")
.find('input')
.val('')
.each(function(key,element){
var $element = $(element),
oldName = $element.attr('name'),
newName;
if(oldName){
newName = oldName.replace(/tree[0-9]+/, 'tree'+(treeCount+1));
$element.attr('name', newName);
}
else {
treeCount--;
}
})
.promise().done(function(){
treeCount++;
});
});
(please don't shoot me)
This is my code. For some reason, the starred line is having a problem. Whenever I load the page, I get /15 like I should. However, when I submit the html form, the output replaces the /15. Is there anyway to make the output come before the /15 instead of replacing it?
<html>
<head>
</head>
<body class="mmmm">
<div class="center">
<script language="JavaScript">
function add(){
var rawScore=document.getElementById('rawScore');
var apScore=document.getElementById('apScore');
var mcPerc=document.getElementById('mcPerc');
rawScore.value = 0;
rawScore.value = Math.round(parseInt(mc.value)
+ parseInt(one.value)*1.1538
+ parseInt(two.value)*.9375
+ parseInt(three.value)*1.25);
mcPerc.value= Math.round(parseInt(mc.value)/60*1000)/10;
if (rawScore.value>=73){
apScore.value="5";
}
else if(rawScore.value>=57){
apScore.value="4";
}
else if(rawScore.value>=49){
apScore.value="3";
}
else if(rawScore.value>=38){
apScore.value="2";
}
else{
apScore.value="1";
}
}
</script>
<form class="bbbb" name="frmf">
Multiple Choice Score:
<input class="ddddd" type="number" id="mc" value="60" min="0" max="60"/>
<FONT COLOR="474747">/60</FONT>
<br/>
Free Response 1 Score:
<input class="aaaaa" type="number" id="one" value="13" min="0" max="13"/>
<FONT COLOR="474747">/13</FONT>
<br/>
Free Response 2 Score:
<input class="aaaaa" type="number" id="two" value="8" min="0" max="8"/>
<FONT COLOR="474747">/8</FONT>
<br/>
Free Response 3 Score:
<input class="aaaaa" type="number" id="three" value="6" min="0" max="6"/>
<FONT COLOR="474747">/6</FONT>
<br/>
<p>
<input type ="button" value="Calculate Score" onClick="add();"/>
<br/>
<br/>
**AP Score:
<output class="apScore" type="text" id="apScore"/> /15**
<p>
<br/>
<br/>
Raw Score:
<output class="rawScore" type="text" id="rawScore"/>
<p>
Multiple Choice Percent:
<output class="mcPerc" type="text" id="mcPerc"/>
</p>
</p>
</p>
</form>
</div>
</body>
</html>
you need to add the corresponding closing tag to your <output> elements. Otherwise, due to a bug in the browser probably, it thinks that what is following it is the value:
**AP Score: <output class="apScore" type="text" id="apScore"></output> /15**
note that IE does not support <output> tag.
what about apScore.value = "3" + apScore.value; ?
that would prepend "3" before the value which is it currently.
generally you could do apScore.value="1" + "/15"; or even apScore.value="1/15";
I'm trying to loop over all inputs in my form that are either "text" or "file".
Here's my form markup:
<form action="" method="post" id="upload_form">
<p>
<label for="name">Skin name:</label><br />
<input type="text" name="name" />
</p>
<p>
<label for="desc">Skin description:</label><br />
<input type="text" name="desc" />
</p>
<p>
<label for="aname">Authors name:</label><br />
<input type="text" name="aname" />
</p>
<p>
<label for="aname">Skin image file:</label><br />
<input type="file" name="skin" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</form>
I basically want to check all of these inputs apart from the submit button. Here's my code so far:
$('#upload_form').submit(function(e) {
$('#upload_form input').each(function(index) {
if( this.type == "input" ) {
}
});
});
But it's wrong, I know. Can anyone tell me how to iterate over each input that is either a text or file input?
Thanks.
You can use the filter or the not selector to accomplish this.
I believe you could do this:
$('#upload_form').submit(function(e) {
$('#upload_form input').not(':submit').each(function(index) {
...
});
});
I think this would also work:
$('#upload_form').submit(function(e) {
$('#upload_form input').filter('[type=text], [type=file]').each(function(index) {
...
});
});
Use this.tagName It will give you the tag type as an uppercase string.