Foundation checkboxes stop working with jQuery - javascript

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);

Related

Get the text from label of Radiobutton

I have a couple of radio button below. I want to get the text from the radio button I have chosen. For example: House Espresso or Guest Espresso. I have tried to use getElementsByName and for loop to get the checked value but it seems to return nothing.
Here is my HTML code:
<div class="type">
<p>Type<p>
<input type="radio" id="houseEspresso" name="singleEspresso" checked="checked"onclick="addProduct(this)">
<label for="houseEspresso">House Espresso</label><br>
<input type="radio" id="guestEspresso" name="singleEspresso" onclick="addProduct(this)">
<label for="guestEspresso">Guest Espresso</label><br>
</div>
And here is my Javascript code:
var type = document.getElementsByName("singleEspresso")
for (var i=0; i<type.length; i++){
if(type[i].checked){
var title_type=type[i].innerText
console.log(title_type)
}
}
Can anyone give me an idea to fix it? Thank you!
The problem is that you're trying to get innerText from the <input>, which has none. You need to get the <label>'s text:
for (var i=0; i<type.length; i++){
if(type[i].checked){
var title_type=type[i].nextElementSibling.innerText
console.log(title_type)
}
}
You need to find a checked input, for that you can use :checked css selector. Then you can pick any value from input DOM element which ties it to label (in your case it's id). And basing on the id you can find corresponding label.
const selectedRadioInput = document.querySelector('[name=singleEspresso]:checked');
const inputId = selectedRadioInput.id;
const label = document.querySelector(`[for=${inputId}]`);
console.log(label.innerText);
Working demo: https://jsfiddle.net/yo18mx9k/2/
You can set a value to input radio: <input type="radio" value="1">
Then just get the buttons and see which one is checked, like this:
let house = document.getElementById('houseEspresso');
let guest = document.getElementById('guestEspresso');
if (house.checked) {
console.log(house.value);
} else if (guest.checked) {
console.log(guest.value);
}
However, I would recommend that you take a look at jQuery so you can make it easier:
$("input[name='singleEspresso']:checked").val();

Script not working in cell in every row in table

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.

How to get data attribute from radio button with JavaScript?

I want to get the data-price value from radio button which is checked. I tried something like that:
<input type="radio" name="vehicletype" id="vehicletype" value="{{$vehicletypeData->id}}" data-price="{{$vehicletypeData->km_rate}}" required="">
var vehicleTyp=document.getElementById("vehicletype");
var vetselindx=vehicleTyp.options[vehicleTyp.selectedIndex];
var prikm=vetselindx.getAttribute("data-price");
But this does not work. How can I solve this issue?
document.getElementById("vehicletype");
This gets the element with that id. The single element with that id. Multiple elements in a document cannot share an id.
vehicleTyp.options
Select elements have options. Radio buttons do not.
To find the checked element you should:
Get all the radio buttons. Consider getElementsByName
Loop over them until you find one where the checked property is true
Once you have found the element you are looking for you can use getAttribute("data-price"); or the dataset property.
You can reference the custom data- attributes of an element like so:
const el = document.getElementById("vehicletype");
const price = el.dataset.price;
For more information see the MDN docs on using data attributes.
Note: If you have a second dash in the attribute name e.g. data-price-new the dataset object property will reflect this in camelcase. dataset.priceNew
Working code, using getElementsByName
<input class="form-check-input" type="radio" data-type="one-time" name="payment-radio-btn" value="200" id="flexRadioDefault1" checked />One Time
<input class="form-check-input" type="radio" data-type="two-time" name="payment-radio-btn" value="300" id="flexRadioDefault1"/>Two time
<p> <button onClick="performAction()">Submit</button> </p>
function performAction(){
var amount = 0;
var type = '';
var radios = document.getElementsByName('payment-radio-btn');
for (var radio of radios) {
if (radio.checked) {
amount = radio.value;
type = radio.getAttribute("data-type");
}
}
alert(type)
}
Codepen-link

If checked, show different checkbox

I am in need of building a form, all checkboxes, which show one after another. So if one checkbox is checked, another shows below. Only when the one above is checked.
The form will contain hundreds of checkboxes as many options. so Ifelse statements wouldn't be suitable.
The data for each checkbox will be parsed from xml file.
The only code that seems to stick for this is
$('#chkCheckBox').on('click', function (){
var nextID, body, nextEl;
nextID = $(this).attr(target);
nextEl = $('#' + nextID);
if(nextEl.style.visibility == 'hidden') {
nextEl.style.visibility = 'display'
}
})
Just after a little guidance please. Hope I made sense, feel like I'm going round in circles.
nextEl is a jquery object, not a DOM object, so has no style property. Use jquery .show() and .is()
if(!nextEl.is(':visible')) {
nextEl.show()
}
You also appear to be using the same id for every checkbox (chkCheckBox), dont do this, instead use a class and attach your jquery event to that.
$('.cb').on('click',function(){
nextID = $(this).attr('target');
nextEl = $('#' + nextID);
if(!nextEl.is(':visible')) {
nextEl.show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><input id="cb1" type="checkbox" class="cb" target="cb2"></div>
<div><input id="cb2" type="checkbox" class="cb" target="cb3" style="display:none"></div>
<div><input id="cb3" type="checkbox" class="cb" target="cb4" style="display:none"></div>

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>

Categories

Resources