document.getElementById('').display=block not working - javascript

In the following document, when someone clicks radios (which are in a table) function StOptnClkd is called. It accomplishes everything but the most important thing. There are two elements that need to switch from being diplayed to not displayed- namely, - AmxDisc and stOptnsTbl. These elements are displayed based on the selection on the radio buttons and check boxes.Please help me. I am a newbie trying to learn to code
I have attached the following code
<script type="text/javascript">
function StOptnClkd(clicked_id)
{
//alert(clicked_id)
var strvid = clicked_id;
var StVal = document.getElementById(strvid).value;
document.getElementById("STtypCptrd").checked="Checked";
document.getElementById("cntctpe").innerHTML=StVal;
document.getElementById('Autonote').value = document.getElementById('Autonote').value+"Spke to: " + StVal; + ", ";
document.getElementById("AmxDisc").display="Block" // this doesnt show
document.getElementById("stOptnsTbl").display="None" // this doesnt get hidden
}
</script>
<table id="stOptnsTbl" border cellspacing="50px" style="text-align: center; border: 1px solid black; border-collapse: collapse;float: left; display: none">
<tr> <!--All Party Options-->
<td width="110px" id ="CMOptn" class="stOptions">
<label class="container1" style="float:Left"><Strong> CM</Strong>
<input id= "optstCM" type="radio" value ="CM" Name="stPrtysel" onclick="StOptnClkd(this.id)">
<span class="checkmark1"></span>
</label>
</td>
<td width="110px" id ="UTPOptn" class="stOptions">
<label id="lblUPT" class="container1" style="float:Left"><Strong> UTP</Strong>
<input id= "optUTP" type="radio" value ="UTP" Name="stPrtysel" checked="checked" onclick="StOptnClkd(this.id)" >
<span class="checkmark1"></span>
</label>
</td>
<td width="110px" id ="SPOptn" class="stOptions">
<label id="lblSP" class="container1" style="float:Left;"><Strong> SP </Strong>
<input id= "optSP" type="radio" value ="SP" Name="stPrtysel" onclick="StOptnClkd(this.id)" >
<span class="checkmark1"></span>
</label>
</td>
<td width="110px" id ="SUPOptn" class="stOptions">
<label id="lblSUP" class="container1" style="float:Left;"><Strong> SUP </Strong>
<input id= "optSUP" type="radio" value ="SUP" Name="stPrtysel"onclick="StOptnClkd(this.id)" >
<span class="checkmark1"></span>
</label>
</td>
<td width="110px" id ="ATPOptn" class="stOptions">
<label id="lblATP" class="container1" style="float:Left;"><Strong> ATP </Strong>
<input id= "optATP" type="radio" value ="ATP" Name="stPrtysel"onclick="StOptnClkd(this.id)" >
<span class="checkmark1"></span>
</label>
</td>
<td width="110px" id ="ATTOptn" class="stOptions">
<label id="lblATT" class="container1" style="float:Left;"><Strong> ATT </Strong>
<input id= "optATT" type="radio" value ="AM" Name="stPrtysel" onclick="StOptnClkd(this.id)">
<span class="checkmark1"></span>
</label>
</td>
<td width="110px" id ="AMOptn" class="stOptions">
<label id="lblAM" class="container1" style="float:Left;"><Strong> AM </Strong>
<input id= "optAM" type="radio" value ="AM" Name="stPrtysel" onclick="StOptnClkd(this.id)" >
<span class="checkmark1"></span>
</label>
</td>
</span>
</span>
</tr>
</table>
<span width="100%" id="AmxDisc" style="display:none;">
has referred your account to for resolution.
EDIT: IT IS THERE, coudnt post all the code here, If you guys need the whole code tell me, I can mail it. or find a way to put it here
Edit2: I did the style.display change. It still doesnt do it. IN console, it shows error saying unexpected identfier at that line

document.getElementById("AmxDisc").style.display="block"

Related

Issue in functioning of radio input in dynamically adding row through jQuery

A new row is dynamically creating on clicking "add Row" button through function in jQuery.
But when I select radio input in new row then selected value of previous radio input is removing.
Please run and see the codes as below:
enter image description here
function add_row(table_row_count)
{
$("#add-row_"+table_row_count).hide();
$("#delete-row_"+table_row_count).hide();
var table_row_count = parseInt(table_row_count);
table_row_count += 1;
var markup =
'<tr id="tbl_row_'+table_row_count+'" >'+
'<td><label>'+table_row_count+'</label></td>'+
'<td>'+
'<label>Value in Range? :</label>'+
'<input type="radio" name="option" id="option_1_row_'+table_row_count+'" value="1" > YES'+
'<input type="radio" name="option" id="option_2_row_'+table_row_count+'" value="2" > NO'+
'</td>'+
'<td id="capacity_from_row_'+table_row_count+'" >'+
'<label>Range From :</label><br>'+
'<input type="text" name="capacity_from[]" id="capacity_from_'+table_row_count+'" />'+
'</td>'+
'<td>'+
'<label id="lbl_capacity_range_'+table_row_count+'" >Range Upto :</label><br>'+
'<input type="text" name="capacity_upto[]" id="capacity_upto_'+table_row_count+'" />'+
'</td>'+
'<td class="align-middle"></i> Add Row</td>'+
'<td class="align-middle"></i> Delete Row</td>'+
'</tr>';
var table = $("#tbl_details tbody");
table.append(markup);
}
function delete_row(table_row_count)
{
var r = confirm("Are you sure to delete row");
if(r == false){
return;
}
var table_row_count = parseInt(table_row_count);
var previous_row = table_row_count - 1;
$("#add-row_"+previous_row).show();
if(previous_row != 1){
$("#delete-row_"+previous_row).show();
}
$("#tbl_row_"+table_row_count).remove();
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</head>
<body>
<h3>Enter Details</h3>
<table class="table table-striped" id="tbl_details">
<tbody>
<tr id="row_1">
<td>1.</td>
<td>
<label>Value in Range? :</label>
<input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
<input type="radio" name="option" id="option_2_row_1" value="2" > NO
</td>
<td id="capacity_from_row_1" >
<label>Range From :</label><br>
<input type="text" name="capacity_from[]" id="capacity_from_1" />
</td>
<td>
<label id="lbl_capacity_range_1" >Range Upto :</label><br>
<input type="text" name="capacity_upto[]" id="capacity_upto_1" />
</td>
<td class="align-middle"></i> Add Row</td>
<td class="align-middle"></td>
</tr>
</tbody>
</table>
</body>
</html>
How to solve the issue. kindly help me.
Thanks in advance.
Different radio button groups are created when the name attribute of the radio buttons is different. Also, in the solution below, I made it easier to express dynamic content by using template literals.
Note the following statement in the dynamic element written into the markup variable in the add_row() method:
<input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
<input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO
/* This variable will be used to create new radio button groups. */
let counter = 0;
function add_row(table_row_count) {
$("#add-row_"+table_row_count).hide();
$("#delete-row_"+table_row_count).hide();
var table_row_count = parseInt(table_row_count);
table_row_count += 1;
/* With each iteration, the content of the counter variable is incremented. */
++counter;
var markup =
`<tr id="tbl_row_${table_row_count}">
<td>
<label>${table_row_count}</label>
</td>
<td>
<label>Value in Range? :</label>
<!-- Note the name="option${counter}" statement so that the radio buttons have different groups. -->
<input type="radio" name="option${counter}" id="option_1_row_${table_row_count}" value="1"> YES
<input type="radio" name="option${counter}" id="option_2_row_${table_row_count}" value="2"> NO
</td>
<td id="capacity_from_row_${table_row_count}">
<label>Range From :</label><br>
<input type="text" name="capacity_from[]" id="capacity_from_${table_row_count}"/>
</td>
<td>
<label id="lbl_capacity_range_${table_row_count}">Range Upto :</label><br>
<input type="text" name="capacity_upto[]" id="capacity_upto_${table_row_count}"/>
</td>
<td class="align-middle">
<a href="javascript:void(0)" class="text-success add-row" id="add-row_${table_row_count}" onClick="add_row('${table_row_count}');" >
<i class="fa fa-plus fa-lg text-success" aria-hidden="true"></i> Add Row
</a>
</td>
<td class="align-middle">
<a href="javascript:void(0)" class="text-danger delete-row" id="delete-row_${table_row_count}" onClick="delete_row('${table_row_count}');" >
<i class="fa fa-trash fa-lg text-danger" aria-hidden="true"></i> Delete Row
</a>
</td>
</tr>`
var table = $("#tbl_details tbody");
table.append(markup);
}
function delete_row(table_row_count) {
var r = confirm("Are you sure to delete row");
if(r == false){
return;
}
var table_row_count = parseInt(table_row_count);
var previous_row = table_row_count - 1;
$("#add-row_"+previous_row).show();
if(previous_row != 1){
$("#delete-row_"+previous_row).show();
}
$("#tbl_row_"+table_row_count).remove();
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="add.js"></script>
</head>
<body>
<h3>Enter Details</h3>
<table class="table table-striped" id="tbl_details">
<tbody>
<tr id="row_1">
<td>1.</td>
<td>
<label>Value in Range? :</label>
<input type="radio" name="option" id="option_1_row_1" value="1" checked="checked" > YES
<input type="radio" name="option" id="option_2_row_1" value="2" > NO
</td>
<td id="capacity_from_row_1" >
<label>Range From :</label><br>
<input type="text" name="capacity_from[]" id="capacity_from_1" />
</td>
<td>
<label id="lbl_capacity_range_1" >Range Upto :</label><br>
<input type="text" name="capacity_upto[]" id="capacity_upto_1" />
</td>
<td class="align-middle"></i> Add Row</td>
<td class="align-middle"></td>
</tr>
</tbody>
</table>
</body>
</html>
This is happening because you are using the same name for radio button. And it is default behavior of radio that if you are using the same name for radio button then only one can be selected at time.
For Example
1.) If you have two radios with same name
Only one value can be selected at a time.
2.) Now after adding another row your code will look like
<input name="option" type="radio" value="true"/>
<input name="option" type="radio" value="false"/
<input name="option" type="radio" value="true"/>
<input name="option" type="radio" value="false"/>
name is same for all radio buttons so only one will be selected at a time.
Fix:
In order to fix this issue while adding new row append row number in front of name. That will fix the issue like you did for id attribute.
'<td>'+
'<label>Value in Range? :</label>'+
'<input type="radio" name="option_'+table_row_count+'" id="option_1_row_'+table_row_count+'" value="1" > YES'+
'<input type="radio" name="option_'+table_row_count+'" id="option_2_row_'+table_row_count+'" value="2" > NO'+
'</td>'+
Fixing this will fix the issue.
*** Change dynamic radio input name. here, your code create all dynamic radio input with the same name. ***

Check multiple checkboxes with one global funtion

I am trying to select a list of checkboxes. The inputs are generated dynamically and there is more than one list of checkboxes - so I created a global function by sending in the id of the < table > so that the correct list of checkboxes are checked/unchecked.
I think the looping of the nodes in the nodelist is causing the problem but in my mind, it makes sense, but the checkboxes are not checking and there is no error popping up either.
function checkAll(name) {
var nodeList = $(name).next('input[type="checkbox"]');
var nodes = $(nodeList);
nodes.each(function(node) {
if (!node.disabled) {
node.checked = true;
}
});
}
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" onclick="javascript:checkAll('LocationsTable');">All</button>
<button type="button" onclick="javascript:uncheckAll('LocationsTable');">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
</td>
</tr>
</table>
You can use find here very well.
Consider that your name is an ID, so put in fron of your name the hashtag #name.
Also I would recommend using an event listener. I updated your code to use it therefore I gave your btn an id.
document.getElementById('btn').addEventListener('click', function(){checkAll('LocationsTable')})
function checkAll(name) {
var nodeList = [...$(`#${name}`).find('input[type="checkbox"]')];
nodeList.forEach(function(node) {
if (!node.disabled) {
node.checked = true;
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button id='btn' type="button" >All</button>
<button type="button" onclick="javascript:uncheckAll('LocationsTable');">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store" value="Store"> <span id="StoreName">Store 1</span>
</td>
</tr>
</table>
simply use querySelectorAll() :
function checkAll(name)
{
document.querySelectorAll(`#${name} input[type=checkbox]`).forEach(nod=>
{
if (!nod.disabled) nod.checked = true;
});
}
You want to prepend the selector passed to the functions with a # - an id selector. Then all you need in the function is:
$(name).find('input[type="checkbox"]').not(':disabled').prop('checked',true);
DEMO
function checkAll(name) {
$(name).find('input[type="checkbox"]').not(':disabled').prop('checked',true);
}
function uncheckAll(name) {
$(name).find('input[type="checkbox"]').not(':disabled').prop('checked',false);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" onclick="javascript:checkAll('#LocationsTable');">All</button>
<button type="button" onclick="javascript:uncheckAll('#LocationsTable');">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store1" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store2" value="Store"> <span id="StoreName">Store 2</span>
<input type="checkbox" name="Store" id="Store3" value="Store"> <span id="StoreName">Store 3</span>
<input type="checkbox" name="Store" id="Store4" value="Store" disabled> <span id="StoreName">Store 4</span>
</td>
</tr>
</table>
OPTION 2
However, I would not advise use of inline JS. Separate your JS, CSS, and HTML as in the following demo:
$('button.all').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',true);
});
DEMO
$('button.all').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',true);
});
$('button.none').on('click', function() {
//this refers to button.none
$(this)
//select tabl
.closest('table')
//select checkbox and uncheck
.find('input[type="checkbox"]').not(':disabled').prop('checked',false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" class="all">All</button>
<button type="button" class="none">None</button>
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store1" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store2" value="Store"> <span id="StoreName">Store 2</span>
<input type="checkbox" name="Store" id="Store3" value="Store"> <span id="StoreName">Store 3</span>
<input type="checkbox" name="Store" id="Store4" value="Store" disabled> <span id="StoreName">Store 4</span>
</td>
</tr>
</table>
OPTION 3
Alternatively, you can use one button to toggle all the checkboxes.
$('button.toggle').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',function() {return !this.checked});
});
DEMO
$('button.toggle').on('click', function() {
//this refers to button.all
$(this)
//go up the tree to select the table
.closest('table')
//go down to the checkboxes and check them
.find('input[type="checkbox"]').not(':disabled').prop('checked',function() {return !this.checked});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table summary="User locations" id="LocationsTable">
<tr>
<th>
<input type='hidden' name='StoreSelector' id='StoreSelector' value='true'>
Other locations (multi-store)
<button type="button" class="toggle">All</button>
<!--button type="button" class="none">None</button-->
</th>
</tr>
<tr id="LocationRow">
<td>
<input type="checkbox" name="Store" id="Store1" value="Store"> <span id="StoreName">Store 1</span>
<input type="checkbox" name="Store" id="Store2" value="Store"> <span id="StoreName">Store 2</span>
<input type="checkbox" name="Store" id="Store3" value="Store"> <span id="StoreName">Store 3</span>
<input type="checkbox" name="Store" id="Store4" value="Store" disabled> <span id="StoreName">Store 4</span>
</td>
</tr>
</table>
NOTE
Please note that in each option no reference is made to the id of the particular table in question as the event handler keeps the actions within the particular table whose button was clicked.

onsubmit Function Issues

As I have almost no knowledge of HTML and I had no idea where to ask, I decided to come here. I am trying to edit HTML Weebly web editor generated and add a "contact us" form which will direct messages to my email. I found some source code on the web and tried to incorporate it with the form Weebly generated for me, however I have not had any success. My code is below:
<div>
<form enctype="multipart/form-data" name="contactform" method="post" action="" onsubmit="myFunction()">
<div id="466589977852666939-form-parent" class="wsite-form-container" style="margin-top:10px;">
<ul class="formlist" id="466589977852666939-form-list">
<h2 class="wsite-content-title" style="text-align:left;">SEND US AN EMAIL</h2>
<div><div class="wsite-form-field" style="margin:5px 0px 5px 0px;">
<label class="wsite-form-label" for="Email_Address">Email <span class="form-required">*</span></label>
<div class="wsite-form-input-container">
<input id="Email_Address" class="wsite-form-input wsite-input wsite-input-width-370px" type="text" name="Email_Address" maxlength="100" />
</div>
<div id="instructions-270584481949385592" class="wsite-form-instructions" style="display:none;"></div>
</div></div>
<div><div class="wsite-form-field" style="margin:5px 0px 5px 0px;">
<label class="wsite-form-label" for="Your_Message">Your Message <span class="form-required">*</span></label>
<div class="wsite-form-input-container">
<textarea id="Your_Message" class="wsite-form-input wsite-input wsite-input-width-370px" name="Your_Message" style="height: 200px"></textarea>
</div>
<div id="instructions-137987539423347553" class="wsite-form-instructions" style="display:none;"></div>
</div></div>
</ul>
</div>
<div style="text-align:left; margin-top:10px; margin-bottom:10px;">
<input type='submit' style='position:absolute;top:0;left:-9999px;width:1px;height:1px' /><a class='wsite-button' ><span class='wsite-button-inner'>Submit</span></a>
</div>
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
</div>
It obviously has something to do with the button click not being registered, so I made my own much simpler form to test it out.
<form name="contactform" method="post" action="" onsubmit="myFunction()">
<table width="400px" class="contactform">
<tr>
<td valign="top">
<label for="Email_Address" class="required">Email Address<span class="required_star"> * </span></label>
</td>
<td valign="top">
<input type="text" name="Email_Address" id="Email_Address" maxlength="100" style="width:230px">
</td>
</tr>
<tr>
<td valign="top">
<label for="Your_Message" class="required">Your Message<span class="required_star"> * </span></label>
</td>
<td valign="top">
<textarea style="width:230px;height:160px" name="Your_Message" id="Your_Message" maxlength="2000"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center" >
<br /><br />
<input type="submit" value=" Submit Form " style="width:200px;height:40px">
<br /><br />
</td>
</tr>
</table>
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
And in this case, the function actually fired! So now I am unsure as to what the difference is between my first example, and my second much simpler piece of code. Could anyone help me out?
You could add an onclick() to the submit <a> tag to submit the form.
Like so, change...
<a class='wsite-button' ><span class='wsite-button-inner'>Submit</span></a>
To...
<a class="wsite-button" onclick="document.contactform.submit(); return false;"><span class="wsite-button-inner">Submit</span></a>
This is because in your simplified example you used a Submit button.
Where as in you original form the button is moved out of the screen using CSS and only the text 'Submit' is left there. And your function triggers when the input is clicked, not the text.
This is the CSS style attributes that are hiding the button:
position: absolute;
top: 0;
left: -9999px;
width: 1px;
height: 1px;
Replace this:
<input type="submit" style="position:absolute;top:0;left:-9999px;width:1px;height:1px">
By this:
<input type="submit" />
The button will reappear and clicking on it will trigger your message box.
Here is the JSFiddle demo

When I pass to another radio button both buton's values come

I want to do two radio buttons. Their names will be car and home. If I click car, an input box about the car section will be shown and if I click home, an input box about the home will be shown.
I have found an example about this and I have a problem about it. The codes are below.
<body>
<script type="text/javascript">
function toggleMe(obj, a)
{
var e=document.getElementById(a);
if(!e)return true;
e.style.display="block"
return true;
}
function toggleMe2(obj, a)
{
var e=document.getElementById(a);
if(!e)return true;
e.style.display="none"
return true;
}
</script>
<form name="theForm">
Type<br>
<input type="radio" name="married" value="yes" onclick="return toggleMe(this, 'Car')"> Car
<input type="radio" name="married" value="yes" onclick="return toggleMe(this, 'Home')"> Home<br>
<div id="Car" style="display: none; margin-left: 20px;">
<table>
<tr>
<td>Car InputBox</td>
<td style="text-align: right;"><input name="name" type="text"></td>
</tr>
</table>
</div>
<div id="Home" style="display: none; margin-left: 20px;">
<table>
<tr>
<td>Home InputBox:</td>
<td style="text-align: right;"><input name="name" type="text"></td>
</tr>
</table>
</div>
</form>
</body>
Output of these codes
If I click the car first, the input box of the car section is shown. If I click the home first, the input box of the home section is shown. After I click the car or home first (doesn't matter) if I click another one, both input boxes are shown.
How can I solve this problem? When I click home, the home input box should be shown and when I click car, the car input box should be shown as well. Not both of them.
HTML
<div>
<input type="radio" name="option" value="car" onclick="toggleInput(this)" /> Car
<input type="radio" name="option" value="home" onclick="toggleInput(this)" /> Home
</div>
<div id="car-input-group" class="hide">
Car InputBox
<input name="name" type="text" />
</div>
<div id="home-input-group" class="hide">
Home InputBox
<input name="name" type="text" />
</div>
Javascript
function toggleInput(obj){
var a =document.getElementsByClassName("hide");
for(var i=0; i<a.length; i++){
a[i].style.display = "none";
}
document.getElementById(obj.value + "-input-group").style.display = "block"
}
css
.hide{
display: none
}
Working example: http://plnkr.co/edit/wPdTldCXG0LTJWEtzIxE?p=preview
What about this? Using jquery it's easier. I made it universal, so you could add more radio buttons (using myradio and myinput css classes) without touching the JS.
$( "input.myradio" ).click(function() {
$( "div.myinput").hide();
$( "div#"+$(this).attr('id')).toggle( "slow", function() {
// Animation complete.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="theForm">
Type<br>
<input id="Car" type="radio" name="married" class="myradio" value="yes" />Car
<input id="Home" type="radio" name="married" class="myradio" value="yes" />Home<br>
<div id="Car" class="myinput" style="display: none; margin-left: 20px;">
<table>
<tr>
<td>Car InputBox</td>
<td style="text-align: right;"><input name="name" type="text"></td>
</tr>
</table>
</div>
<div id="Home" class="myinput" style="display: none; margin-left: 20px;">
<table>
<tr>
<td>Home InputBox:</td>
<td style="text-align: right;"><input name="name" type="text"></td>
</tr>
</table>
</div>
</form>
JSFiddle

javascript class sees multiple DOMs in each iteration? jquery .each getting confused

I have quite strange problem, I have simple quiz engine which should restart it self if user doesn't pass with 70% and more.
Everything works ok but when i re-init the script, in next iteration it seems like it sees all questin divs more times. (as many times as many times you failed) so it makes me a mess since every other calculation is based on that.
here is everything to see: http://jsfiddle.net/xdgrh/DhTQw/2/
You can replicate the issue if you choose B for the first question and anything else for other questions. Than it will tell you to click restart because you failed.
In next iteration again choose B and look in feedback. (i checked in log too, it reads everything like there is each question doubled.) And so on as many iterations you make, that many times it calculates everything
html here: (because it must be in post by stack rules)
(Focus should be in $('.btnNext').click... and in $(".box:visible input:radio").each(function(index, value)... there it counts things two-three.. more times.. depending on how may times you fail)
<div id="lliquizContent">
<div id="headerX">
<h1>Task 1: Work with Today's Client (Final task) </h1>
</div>
<div class="feedback">
<div class="feedback-title">
FEEDBACK TITLE
</div>
<div class="feedback-text">
FEEDBACK TEXT
</div>
<img src="/Resource/GetResource/CRSTechModule1/feedback.m1s29.1.png" border="0" />
<div style="clear:both;"> </div>
<div class="feedback-footer">
<div class="btnFeedbackNext">Next Question ></div>
<div class="score"><strong>Score: </strong><span class="score"></span> %</div>
</div>
</div>
<div class="box" type="1">
<div class="headerX">
<p>Task question 1 of 4</p>
</div>
<div class="question qsize1">
<div class="questionText">Based on Anne’s original email, how should you respond?</div>
<div class="answers">
<table>
<tr>
<td><input type="radio" name="" value="0" /> </td>
<td><label>Email Anne to set up a face-to-face meeting.</label></td>
<td>
<feedback>
<fbtitle>Incorrect. You did not select the best approach for responding to Dr. Anne Jones. Click Next to view the next question.</fbtitle>
<fbtext>"I’d like to be able to meet with you, but as I said in my original email, I am just too busy! Please email me your thoughts about homes that might be suitable for my situation."</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="1" /> </td>
<td><label>Email Anne and ask her to register on your website.</label></td>
<td>
<feedback>
<fbtitle>Correct! You selected the best approach for responding to Dr. Anne Jones. Click Next to view the next question.</fbtitle>
<fbtext>"Thanks for getting back to me. I’ll look at the two homes you mentioned and try to register on your website when I get a chance. I am very excited about getting a new home in Springfield. Thanks for helping me."</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="0" /> </td>
<td><label>Email Anne to qualify her as a possible lead.</label></td>
<td>
<feedback>
<fbtitle>Incorrect. You did not select the best approach for responding to Dr. Anne Jones. Click Next to view the next question.</fbtitle>
<fbtext>"I really don’t have any more information to give you at this time. As I wrote in my original email, I think new construction would be ideal for me. Can’t you just email me information on homes that are available? I don’t have a lot of time."</fbtext>
</feedback>
</td>
</tr>
</table>
</div>
</div>
<div style="clear: both;"> </div>
<div class="attachments">
<a id="transcript-button1" href="#" lliQuizTitle="Transcript 1 lliQuizTitle">Approach #1</a> |
<div style="display: none;" id="TRANSCRIPT-TEXT1" lliQuizTitle="Transcript 1 lliQuizTitle">transcript 1</div>
<a id="transcript-button2" href="#">Approach #2</a> |
<div style="display: none;" id="TRANSCRIPT-TEXT2" lliQuizTitle="Transcript 2 lliQuizTitle">transcript 2</div>
<a id="transcript-button3" href="#">Approach #3</a>
<div style="display: none;" id="TRANSCRIPT-TEXT3" lliQuizTitle="Transcript 3 lliQuizTitle">transcript 3</div>
</div>
<div class="btnContainer"><a class="btnNext">SUBMIT</a></div>
<div class="instructions">Select the correct answer then click the forward arrow to continue.</div>
<div class="rightAttachmentBox">
<a id="transcript-button4" href="#">Click here</a><br />
to see the email from<br />
Anne Jones
<div style="display: none;" id="TRANSCRIPT-TEXT4" lliQuizTitle="Transcript 4 lliQuizTitle" lliQuizTop="20" lliQuizLeft="200" lliQuizWidth="300" lliQuizHeight="300">
transcript 4 transcript 4 transcript 4
</div>
</div>
</div>
<div class="box" type="2">
<div class="headerX">
<p>Task question 2 of 4</p>
<div class="questionText">Based on Anne’s original email, how should you respond?</div>
</div>
<div class="questions qsize2">
<table>
<tr>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
</tr>
<tr>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
<td>
<div class="question"> <div class="questionText">Based on Anne’s original email, how should you respond?</div> <div id="answers"> <table> <tr> <td><input type="radio" name="" value="1" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 1.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 2.</td> </tr> <tr> <td><input type="radio" name="" value="0" /> </td> <td><label>Email Anne to set up a face-to-face meeting.</label></td> <td id="fedback_content">Question response 3.</td> </tr> </table> </div> </div>
</td>
</tr>
</table>
</div>
<feedback>
<correct>
<fbtitle>Correct...</fbtitle>
<fbtext>"Text..."</fbtext>
</correct>
<incorrect>
<fbtitle>Incorrect...</fbtitle>
<fbtext>"Text...."</fbtext>
</incorrect>
</feedback>
<div style="clear: both;"> </div>
<div class="btnContainer"><a class="btnNext">SUBMIT</a></div>
<div class="instructions">Select the correct answer then click the forward arrow to continue.</div>
</div>
<div class="box qsize3" type="3">
<div class="headerX">
<p>Task question 3 of 4</p>
<p>Select the best Target group for you based on your data. Next, select your Rationale and click Submit to get your feedback. You may view your client analysis at any time to help you choose an approach.</p>
<div class="questionText">I’ve reviewed your client analysis and I have an idea of where you might be able to add a lot of value to your clients. But I want to know what you think.<br />
What target group do you think it makes the most sense for you to select? Why?</div>
</div>
<div class="questions qsize3">
<table>
<tr valign="top" >
<td>
<div class="question">
<div class="questionText">Target group</div>
<div id="answers">
<table>
<tr>
<td><input type="radio" name="" value="0" /></td>
<td><label> Doctors and nurses transferring to Springfield.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext>I think you should focus on transfers into Springfield, however, I think that group may be a little too specific.</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="0" /></td>
<td><label>Home sellers with older homes looking to purchase new construction.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext>I thought you didn’t like to work with this group.</fbtext>
</feedback>
</td>
</tr>
<tr>
<td>
<input type="radio" name="" value="0" />
</td>
<td><label>Home buyers looking for older homes outside of Springfield.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext>I am not sure why you picked this group. I thought you liked new construction.</fbtext>
</feedback>
</td>
</tr>
<tr>
<td>
<input type="radio" name="" value="1" />
</td>
<td><label>First-time home buyers and transfers to the area looking for new construction.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext></fbtext>
</feedback>
</td>
</tr>
</table>
</div>
</div>
</td>
<td>
<div class="question">
<div class="questionText">Rationale</div>
<div id="answers">
<table>
<tr>
<td><input type="radio" name="" value="1" /></td>
<td><label>I only want to focus on one specific group that is associated with the hospital.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext>For the rest of this meeting, I think we should focus on first-time home buyers and transfers to the area looking for new construction.</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="0" /></td>
<td><label>I don’t want to pick between two of the buyer types with whom I enjoy working.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext>For the rest of this meeting, I think we should focus on first-time home buyers and transfers to the area looking for new construction.</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="0" /></td>
<td><label>Older homes have a lot more character than new construction.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext>For the rest of this meeting, I think we should focus on first-time home buyers and transfers to the area looking for new construction.</fbtext>
</feedback>
</td>
</tr>
<tr>
<td><input type="radio" name="" value="0" /></td>
<td><label>Springfield is not expanding and there aren't new construction homes.</label></td>
<td>
<feedback>
<fbtitle></fbtitle>
<fbtext>I agree that you should focus on first-time home buyers and transfers looking for new construction. But why did you select them?</fbtext>
</feedback>
</td>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</div>
<feedback>
<correct>
<fbtitle>Correct! You selected an appropriate target market and the best rationale. Click Next to view the next question.</fbtitle>
<fbtext>"I agree! I think you will be very happy working with this group and it sounds like you are well on your way to becoming a new construction expert. This expertise will add value to the service you provide your clients."</fbtext>
</correct>
<incorrect>
<fbtitle>You have a red X next to each incorrect answer. You did not select the best choices here. Click Next to view the next question.</fbtitle>
<fbtext></fbtext>
</incorrect>
</feedback>
<div style="clear: both;"> </div>
<div class="btnContainer"><a class="btnNext">SUBMIT</a></div>
<div class="instructions">Select the correct answer then click the forward arrow to continue.</div>
</div>
<div class="box-fail">
Ponovo init... TRY AGAIN...MUST GET 70%+
</div>
<div class="box-success">
It's on, go on...</div>
</div>
And here is s:
var lliQuiz = {
message1: "message1",
message2: "",
feedbackImage: "/image/not/set",
score: 0,
currentTab: 0,
checkFormat: function() {
var $boxes = $('.box'), valid = $boxes.length > 0;
if (valid) {$boxes.each(function (idx, box) {
var $box = $(this),$qtns = $box.find('.question');
if ($qtns.length == 0) {
valid = false; return false;
} valid = $qtns.filter(function () {
return $(this).find('input[type="radio"]').length < 2;
}).length == 0; if (!valid) { return; }
})
}
if (valid) {return true;} else {return false;exit;}
},
createFeedback: function(boxVisible,type,farray,addScore) {
$('.feedback img').attr('src',lliQuiz.feedbackImage);
if (type == 1) {
$.each(farray, function(i,id){ // NE TREBA FOR EACH??? samo je jedno pitanje...
$('.feedback .feedback-title').text($('input[id='+id+']').nextInDOM('fbtitle').html());
$('.feedback .feedback-text').text($('input[id='+id+']').nextInDOM('fbtext').html());
});
}
if (type == 2) {
if (addScore == true) {
$('.feedback .feedback-title').text($(boxVisible).find('feedback > correct > fbtitle').html());
$('.feedback .feedback-text').text($(boxVisible).find('feedback > correct > fbtext').html());
} else {
$('.feedback .feedback-title').text($(boxVisible).find('feedback > incorrect > fbtitle').html());
$('.feedback .feedback-text').text($(boxVisible).find('feedback > incorrect > fbtext').html());
}
}
if (type == 3) {
if (addScore == true) {
$('.feedback .feedback-title').text($(boxVisible).find('feedback > correct > fbtitle').html());
$('.feedback .feedback-text').text($(boxVisible).find('feedback > correct > fbtext').html());
} else {
var text = "";
$.each(farray, function(i,id){
var br = (i == 0) ? "<br /><br />" : "";
text = text + " " + $('input[id='+id+']').nextInDOM('fbtext').html() + br;
});
$('.feedback .feedback-title').text($(boxVisible).find('feedback > incorrect > fbtitle').html());
$('.feedback .feedback-text').html('"'+text+'"');
}
}
return true;
},
checkAnswers: function() { return 5; },
init: function() {
$('.box, .box-success, .box-fail').fadeOut(100);
$('span.redx').remove();
lliQuiz.score = 0;
lliQuiz.currentTab = 0;
console.log('init poeni: '+lliQuiz.score);
// check format
if (lliQuiz.checkFormat()) {
$('.box:first').fadeIn(1000);
console.log( "LLI - HTML FORMAT OK!!!" );
} else {
$('#lliquizContent').html('<div style="color: red; font-size: 16px; font-weight: bold; text-align: center; width: 100%;">HTML FORMAT ERROR</div>');
console.log( "LLI - HTML FORMAT ERROR!!!" );
}
console.log( "LLI - Quiz Start!" );
var pointsPerQuestion = parseFloat(100 / $('.box').length).toFixed(2);
$(".question").each(function(index,value) {
var groupNumber = ++index;
$(":radio", this).attr("name", "group" + groupNumber).each(function(index,value){
$(this).removeAttr('checked').attr("id","id"+groupNumber+index).nextInDOM('label').attr("for","id"+groupNumber+index);
});
});
$('input').iCheck('uncheck');
$('input').iCheck({ checkboxClass: 'icheckbox_minimal-blue', radioClass: 'iradio_flat-blue' });
// lli idemo dalje...
$('.btnNext').click(function(e) {
e.preventDefault();
var status = true;
var addScore = false;
var carray = []; carray.length = 0;
var xarray = []; xarray.length = 0;
var farray = []; farray.length = 0;
lliQuiz.currentTab++;
$('span.redx').remove();
$(".box:visible input:radio").each(function(index, value){
if($("input:radio[name="+$(this).attr("name")+"]:checked").length == 0) {
status = false;
}
if(value.value == 1 && value.checked == true) {
carray.push($(this).attr("id"));
console.log($(this).attr("id"));
}
if (value.value == 0 && value.checked == true) {
xarray.push($(this).attr("id"));
console.log($(this).attr("id"));
}
if (value.checked == true) {
farray.push($(this).attr("id"));
console.log($(this).attr("id"));
}
});
if (carray.length == $(".box:visible .question").length) {
lliQuiz.score += parseInt(pointsPerQuestion);
if (lliQuiz.score == 99) $('span.score').text(100);
else
$('span.score').text(lliQuiz.score);
addScore = true;
} else {
addScore = false;
if (lliQuiz.score == 0) $('span.score').text(0);
}
if (status == false) {
$("#lliquizContent").block({ message: lliQuiz.message1 , theme: false, timeout: 2500, fadeOut: 400, overlayCSS: {opacity: 0.1, cursor: "default"}, css: {border: '1px solid #333',width: '200px', padding: '10px','border-radius': '7px', color: 'red', '-webkit-border-radius': '7px', '-moz-border-radius': '7px' } });
exit;
} else {
$("#lliquizContent").block({ message: false , theme: false, overlayCSS: {opacity: 0.1, cursor: "default"} });
$.each(xarray, function(i,id){
$('#'+id).prevInDOM('.questionText').prepend('<span class="redx">X</span>');
});
lliQuiz.createFeedback($(".box:visible"),$('.box:visible').attr('type'),farray,addScore);
$(".feedback").fadeIn(1000);
}
});
$('.btnFeedbackNext').click(function() {
console.log('feedback poeni: '+lliQuiz.score);
if ($('.box').length == lliQuiz.currentTab) {
$('.feedback').fadeOut(200);
$('#lliquizContent').unblock();
$('.box:visible').fadeOut(200);
if (lliQuiz.score >= 70) {
$('.box:visible').fadeOut(300);
$('.box-success').fadeIn(1000);
$.hurdleNext(false);
} else {
$('.box-fail').fadeIn(1000);
$.hurdleNext(true);
}
} else {
$('.feedback').fadeOut(300);
$('#lliquizContent').unblock();
$('.box:visible').fadeOut(function(){
$(this).next().fadeIn(1000);
return false;
});
}
});
},
test: function() { alert('lli test'); }
}
lliQuiz.message1 = "Please answer the questions before submiting!";
lliQuiz.feedbackImage = "feedback.m1s29.1.png";
lliQuiz.init();
$('#initButton').click(function(){
lliQuiz.score = 0;
lliQuiz.init();
});
When you click #initButton you are adding another click event handler to your buttons.
Before you init, you should use .unbind(); to clear the events.
$('#initButton').click(function(){
// remove click handler for elements
// use .unbind('click'); specifically to remove click events
$('.btnFeedbackNext').unbind('click');
$('.btnNext').unbind('click');
lliQuiz.score = 0;
lliQuiz.init();
});
Edit: In later versions of jQuery the preffered method is using .off();
Thanks to #AnthonyGrist for pointing that out :)
Here is an example Here

Categories

Resources