Script not working in cell in every row in table - javascript

I have a row/column table with switches, unfortunately the script can't find
the switches in the new column, basically after the end of the cell .
I tried modifying some of the scripts that were posted in the similar posts but
none of them worked. I am pretty much stuck at this point.
Here's my HTML and the java script that does the calculation for the switches:
<div style="margin-left:-178px">
<form action="file:///Users/jason/Desktop/Temp/JACK010.txt" target="_blank">
<font color="white">JACK010</font>
<input type="submit" value="CHECK ADDRESS">
<div id="checkbox-container">
<div style="margin-left:178px">
<div style="margin-top:-18px">
<div>
<input type="checkbox" id="option170">
</div>
</form>
</td>
</tr>
I have a lot of those, within the cell, and finally the JavaScript:
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {};
var $checkboxes = $("#checkbox-container :checkbox");
$checkboxes.on("change", function() {
$checkboxes.each(function() {
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});
Thank you!

Using only $("#checkbox-container :checkbox"); results in only reading the first container with the ID checkbox-container.
If you want to fetch all checkboxes, you should either change the checkbox-container to a class or use the following selector within jQuery:
var $checkboxes = $("div#checkbox-container :checkbox");
It will then loop through all the checkboxes, even if an ID is used instead of a class.
Keep in mind, that the ID of your checkbox (<input type="checkbox" id="option170">) must however change in order to get valid data and all the values you want.
Side note: Please keep your HTML code clean and valid.

Related

Foundation checkboxes stop working with jQuery

If you go here http://passion4web.co.uk/DigiPics/upload and upload a photo, you'll see it brings up some checkbox options to brighten, distort. etc. I am using jquery to clone #photo-template so I can use it multiple times but the problem I am having is the checkboxes will not change when clicked.
This only seems to happen when I add foundation checkboxes to the page using javascript. Here is my method of adding them:
var $template = $("#photo-template");
var $addedPhotos = $("#added-photos");
$addedPhotos.html("");
if(response.length > 0)
{
for(var i in response)
{
var options = response[i];
var template = $template.clone();
template.find(".photo").attr("src", options['Photo URL']);
template.find(".brighten").prop("checked", options['Brighten']);
template.find(".sky").prop("checked", options['Sky']);
template.find(".grass").prop("checked", options['Grass']);
template.find(".distortion").prop("checked", options['Distortion']);
template.find(".description").val(options['Description']);
$addedPhotos.append(template.html());
}
}
You are not using the for attribute of label correctly. An excerpt of your HTML is:
<div class="switch round">
<input type="checkbox" class="sky" name="sky">
<label for="sky"></label>
</div>
The value of the for needs to match an id of a checkbox. It should be:
<div class="switch round">
<input type="checkbox" class="sky" name="sky" id="sky">
<label for="sky"></label>
</div>
Unfortunately since you are cloning it, you also need to make these id's unique. One possible solution:
template.find(".sky")
.prop("checked", options['Sky'])
.prop("id", "sky" + i)
.next() //get the label after it
.prop("for", "sky" + i);

jQuery Adding and Removing Rows Trouble

I'm trying to create a new use for an already implemented tool we use here at work, but I'm very sure I'm doing something wrong.
I can't figure out how to make it delete a row. And even more, I can figure out how to clone everything within .pt-entry, and have it replicated inside of the incremental .pt-entry...but without the user filled in info.
Hopefully this makes sense.
You can check out my Pen here, but here's the code breakdown for the rest of yous:
HTML:
<table class="manage-pt" id="0">
<tr class="pt-entry">
<td class="pt-toggle-group">
<input type="button" class="pt-button togPTbutton" value="?" />
<input type="button" class="pt-button addPTbutton" value="+" />
<input type="button" class="pt-button delPTbutton" value="-" />
</td>
<td class="pt-values">
<div>
<input type="text" class="vendor" placeholder="Vendor Name" />
</div>
<div>
<textarea class="ptCode" name="ptCode" placeholder="Pixel Tag Code" ></textarea>
</div>
<div class="page-select">
<select>
<option value="AllPages">All Pages</option>
<option value="HomePage">HomePage</option>
<option value="VehicleDetailsPage">VehicleDetailsPage</option>
<option value="VehicleSearchResults">VehicleSearchResults</option>
<option value="ContactUsForm">ContactUsForm</option>
</select>
</div>
<div class="area-checkboxes">
<p class="wheretosave">Where?</p>
<input type="checkbox" name="head" /><label for="head">Head</label>
<input type="checkbox" name="body" /><label for="body">Body</label>
</div>
<div class="save-pt">
<input value="SAVE" type="submit" />
</div>
</td>
</tr>
</table>
JavaScript:
// HIDES CURRENT PT & CHANGES TOGGLE BUTTON ICON WHEN CLICKED
$('.togPTbutton').click(function(){
$('.pt-values').slideToggle(25, function() {
if ($('.pt-values').is(':hidden')) {
$('input.togPTbutton').val('?');
}else{
$('input.togPTbutton').val('?');
}
});
});
$(document).ready(function () {
var table = $('.manage-pt'),
rows = $(table).find('tr'),
rowCount = $(rows).length,
addedRow = $(document.createElement('tr')),
addButton = $('.addPTbutton'),
removeButton = $('.delPTbutton');
function addRow(){
var thisRow = $(addedRow).clone(true);
$(thisRow).attr('class','.pt-entry-' + rowCount);
rowCount += 1;
$(thisRow).html('<td>row</td>');
$(table).append(thisRow);
}
function removeRow(){
var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
$(table).remove(items[rowCount - 1]);
rowCount -= 1;
}else{
alert('CANNOT DELETE LAST ROW');
}
}
addButton.click(function(e){
addRow();
});
removeButton.click(function(e){
removeRow();
});
});
Should look close to something like this mockup ...
Alright, I think I found your problem. You are trying to call $(table).querySelectorAll('tr'). .querySelectorAll is a javascript function that you are using with a JQuery selector. This is where your removeRow() function bombs. Try commenting that line out. Then, you will need to find a new way to select the last row, which can easily be done with this:
$(table).find('tr:last').remove();
Final form:
function removeRow(){
//var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
//$(table).remove(items[rowCount - 1]);
$(table).find('tr:last').remove();
rowCount -= 1;
}
else
{
alert('CANNOT DELETE LAST ROW');
}
}
If you want this to work in IE8 and older, you can use this JQuery since you have the number of rows:
$(table).find('tr').eq(rowCount - 1).remove();
in place of:
$(table).find('tr:last').remove();
JSFiddle: http://jsfiddle.net/Em8Q5/2/
EDIT: ------------------------------------------------------------------------------------
Alright, I found a solution being able to delete the current row.
First, allow a parameter into your removeRow function and switch the selector to use closest:
function removeRow(currRow){
//var items = $(table).querySelectorAll('tr');
if (rowCount > 1) {
//$(table).remove(items[rowCount - 1]);
currRow.closest('tr').remove();
rowCount -= 1;
}
else
{
alert('CANNOT DELETE LAST ROW');
}
}
Then you will need to modify your .click function so that it will change dynamically as you add/remove rows/buttons. Also, note the parameter so it knows which row's button is clicked.
//removeButton.click(function(e){
$('body').on("click", ".delPTbutton", function(e) {
removeRow($(this)); //Note the parameter that we added so it knows which row to remove
});
JSfiddle: http://jsfiddle.net/Em8Q5/3/
I check up your code using chrome developer tool and when i clicked the delPTbutton button to remove last row it showed an error in your removeRow Method , The Error Message Is :
(Uncaught TypeError: Object [object Object] has no method 'querySelectorAll')
The Issue Here Is That 'querySelectorAll' Is One Of javascript base api but you use it after a jquery object.
Consider Using $(table).find('tr') Instead .
Ok so thank you #Chad for your help. You were seriously a life saver.
I took what you did, one step further in this new version of the code:
New CodePen
However I now have a very js minor issue. I have it set to turn the ".vendor" input to read only when the relevant stack is closed, however I need to target something other than ".vendor", because it's effecting each clones ".vendor" as well.
Would it be something like:
$(this).parent().next().child().child();?

JQuery - Append to text area that has been modified with Jquery

I am trying to append the value of a div or a input box to my text area. I have this working no problem but if i clear the contents of the text area first with a Jquery action it doesnt allow me to use my append features.
E.g.
<script type="text/javascript">
$(document).ready(function() {
$("#Column1").click(function () {
$("#sql").append($("#Column1").val())
})
$("#Column2").click(function () {
$("#sql").append($("#Column2").html())
})
$("#reset_sql").click(function () {
$("#sql").val('SELECT ')
})
</script>
<div> <input type="checkbox" name="column1" id="column1" value="`Column1`"> column1 </div>
<div id="Column2"> Column2 </div>
<textarea rows="10" cols="80" name="sql" id="sql"><? echo $sql ;?></textarea>
<input type="submit" value="submit" />
<input type="button" value="reset sql" id="reset_sql" />
The input and div lines above are just generic examples but relate exactly to what i'm trying to do.
I dont understand that when i clear the text area with javascript that my appends wont work. I get no JS errors in firefox error console.
thank you
You have several issues with your code: you haven't closed your document.ready callback, you are using the incorrect case when refering to your ID's, and you're using some of the jQuery methods incorrectly. For example, append() appends HTML to an element, whereas you want to update the value.
Your logic isn't quite correct either, since columns won't be removed when you uncheck a checkbox, and the columns won't be comma delimited (it looks like you are building a SQL string here).
I believe something like this is what you're looking for:
$(document).ready(function() {
var $sql = $('#sql');
var initialValue = $sql.val();
$("#column1, #column2").on('change', function () {
var cols = [];
var checked = $('input[type="checkbox"]').filter(':checked').each(function() {
cols.push($(this).val());
});
$sql.val(initialValue + ' ' + cols.join(', '));
})
$("#reset_sql").on('click', function () {
$sql.val(initialValue)
})
});
Working Demo
Your checkbox has an id of 'column1', but your event handler is $("#Column1").click(function () {.
Case matters! Either change the id to 'Column1' or the event handler to look for $('#column1').
Demo

javascript: use getElementByID to populate multiple divs

is there a way to write the same thing clientside using javascript to multiple divs or multiple spots on a page?
I have a php script outputting rows from a database. To edit the contents, I would like to insert a checkbox before each row as with the iphone edit contacts and to do it quickly, I'm trying to use javascript to populate a div with a checkbox before each row using getElemenByID.
One problem is you cannot have more than one div of the same name on a page so I can't write once and have it populate multiple divs of the same name. If I give divs different names than I have to write multiple times which is not appealing especially as the number of rows may vary.
As a related question would checkboxes inserted using javascript even work?
Here is non working code:
js
function edit() }
var box = '<input type="checkbox name=num[]>';
var target = "checkbox";
document.getElementById(target).innerHTML = box;
return;
}//end function
html (generated by PHP from dbase)
<form action="edit.php" method="post">
<a href="javascript:void" onclick="edit()";>edit</a>
<div id="checkbox"></div>Row1 contents<br>
<div id="checkbox"></div>Row2 contents<br>
<form type = "submit" value="Edit">
</form>
Does anyone know a way to do this ie make boxes appear that can then be selected for submission?
Many thanks for any suggestions.
Should be generated using PHP instead, but...
HTML
I'm guessing that you want to use a span element (not a div) for your checkbox placeholder, otherwise you'd have a checkbox on one line, and then "Row1 contents" below the checkbox, versus having the checkbox next to the text.
[X]
Row 1 Contents
versus (span)
[X] Row 1 Contents
<form action="edit.php" method="post" name="frmRows" id="frmRows">
edit
<span class="checkbox"></span>Row1 contents<br>
<span class="checkbox"></span>Row2 contents<br>
<input type = "submit" value="Edit">
</form>
JavaScript
It's not recommended to use .innerHTML in JavaScript unless absolutely necessary (not supported in all browsers, and there are better ways to accomplish the same task.)
function edit() {
var newCb;
var i;
var checkboxList = document.getElementsByClassName( 'checkbox' );
for ( i = 0; i < checkboxList.length; i++ ) {
newCb = document.createElement( 'input' ); // Create a new input element
newCb.setAttribute( 'type', 'checkbox' ); // Set attributes for new element
newCb.setAttribute( 'value', 'SomeValueHere' );
newCb.setAttribute( 'name', 'checkboxName' );
newCb.setAttribute( 'id', 'checkbox-' + i );
checkboxList[i].appendChild( newCB ); // Add checkbox to span.checkbox
}
}
The ID attribute must be unique on each page. You could use the class attribute like this:
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
and then you can use
var check = getElementsByClassName('checkbox');
for (var i=0; i< check.length; i++) {
check[i].innerHTML = box;
}
But... this will not work in IE < 9. If you are using a framework like jQuery they already implemented a workaround for this but with pure JS you have to implement this yourself.
jQuery example
HTML
<div class="checkbox"></div>Row1 contents<br>
<div class="checkbox"></div>Row2 contents<br>
JS
var box = '<input type="checkbox" name="num[]" />';
$(".checkbox").html(box);
The HTML
The first thing to do is to update the generated HTML. In HTML element id attributes should be unique just like field names inside a form. To classify multiple elements as similar you should use the class attribute.
Here is an example of how you could structure the HTML.
<form action="edit.php" method="post">
edit
<div id="row1Identifier" class="editCheckbox"></div>Row1 contents</br>
<div id="row2Identifier" class="editCheckbox"><?div>Row2 contents</br>
<input type="submit" value="Submit">
</form>
The javascript
Using document.getElementsByClassName will return a list of elements with the matching class.
​function edit () {
// set up the variables used in this function
var checkboxDivs = document.getElementsByClassName('editCheckbox'),
i,
loopDiv;
// make the change to each div
for (i = 0; i < checkboxDivs.length; i += 1) {
loopDiv = checkboxDivs[i];
loopDiv.innerHTML = '<input type="checkbox" name="' + loopDiv.id + '">';
}
}​
Even if you could do it with a single line (using jQuery, for exemplo), you would actually be running a loop through all the divs (that's the only way to change something in various elements: change it in each one).
So you can do this with pure JavaScript using a loop to run the modifications in all the divs, getting them by id (the faster way):
for(var i = 0; i < numberOfDivs; i++){
document.getElementById("myElement" + i).innerHTML = box; //concatenating i to a base id
}
You could also use another slower techniques to get elements by tag name or class, or even use a lib such as jQuery.
If you use jquery:
function edit() {
// box = '<input type="checkbox name=num[]>';
var target = "checkbox";
$(".cb").html(box);
return;
}//end function
<form action="edit.php" method="post">
edit
<div class="cb" id="checkbox">aa</div>Row1 contents<br>
<div class="cb" id="checkbox">bb</div>Row2 contents<br>
</form>

Jquery get each div's sub child divs and grab info into an array

I have a some html that looks like this
<div id="main">
<div id="sub_main_1" class="sub_main">
<input type="text" class="sub_name_first" /><br />
<input type="text" class="sub_name_second" /><br />
</div>
<div id="sub_main_2" class="sub_main">
<input type="text" class="sub_name_first" /><br />
<input type="text" class="sub_name_second" /><br />
</div>
</div>
I would like to pull out each sub_main divs information into an array in javascript. So far I have this as my jquery code
$('#main').find('.sub_main').each(
function() {
alert('hi');
});
The alert is just a test that it should show "hi" twice. But this is not working. I am also not clear on how I can store the two inputs in a javascript array. Any help would be great! Thanks,
var array = $('#main input').map(function() {
return $(this).val();
}).get();
EDIT:
Note that this will return the values of all input elements under #main. You can make the $('#main input') selector as specific as you need if not all input elements are desired.
var info = $("#main .sub_main input:text").map(function() {
return $(this).val();
}).get(); // get() converts resulting collection into array
http://api.jquery.com/map/
Are you waiting for the DOM to load?
$(document).ready(function(){
$('#main').find('.sub_main').each(
function() {
alert('hi');
});
});
if you want to pull out the child divs of your 'main' div, use
$('.main>div')
This will select all div children of anything with the class of 'main'.
why not just do something simple like this:
var firsts = [];
var seconds = [];
("#main .sub_main input").each(function(){
var $this = $(this);
if($this.is(".sub_name_first"){
firsts.push($this.val());
} else {
seconds.push($this.val());
}
});
sure, its not the best way, but i just wrote that in 1 minute and it works

Categories

Resources