The code can add attribute checked="checked" on first item already loaded from HTML markup. But, when I added a new "item" radio element, the code cannot include the attribute checked="checked". Why this happens?
I tested using the browser console (F12) to see if attribute would be included or not on respective radio input clicked, but no success so far.
If I not add checked="checked" my value is not stored on sql table. But if I add checked="checked" manually, editing on my browser console, my value is updated with success on sql table.
How can I fix this situation?
jsfiddle
<div id="p_scents">
<p>
<span class="custom_radio">
<input type="radio" id="featured-1" name="s_radio" value="1"> <label for="featured-1">item 1</label>
</span>
</p>
</div>
<span id="add" class="btn btn-sm btn-primary">add</span>
<span id="remove" class="btn btn-sm btn-pub">remove</span>
var i = 1 ;
var scntDiv = $('#p_scents');
function add_track() {
if(i < 30){
i++;
$('<p><span class="custom_radio"><input type="radio" id="featured-'+ i +'" name="s_radio" value="'+ i +'"> <label for="featured-'+ i +'">item '+ i +'</label></span></p>').appendTo(scntDiv);
}
}
function remove_track() {
if(i > 1){
var select = document.getElementById('p_scents');
select.removeChild(select.lastChild);
i--;
}
}
document.getElementById('add').addEventListener('click', add_track, false);
document.getElementById('remove').addEventListener('click', remove_track, false);
$("[name='s_radio']").on("click", function() {
$("[name='s_radio']").attr("checked", false);
$(this).attr("checked", true);
});
Let me clarify few things here so you actually learn something:
you are writing the JS code for something HTML radio buttons do them self's. If you put same name attribute in your case name="s_radio" on them they will automatically uncheck others and just live check on the only clicked one, they just need to have same name, and you already did that. This is called grouping inputs:
Example:
var i = 1 ;
var scntDiv = $('#p_scents');
function add_track() {
if(i < 30){
i++;
$('<p><span class="custom_radio"><input type="radio" id="featured-'+ i +'" name="s_radio" value="'+ i +'"> <label for="featured-'+ i +'">item '+ i +'</label></span></p>').appendTo(scntDiv);
}
}
function remove_track() {
if(i > 1){
var select = document.getElementById('p_scents');
select.removeChild(select.lastChild);
i--;
}
}
document.getElementById('add').addEventListener('click', add_track, false);
document.getElementById('remove').addEventListener('click', remove_track, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="p_scents">
<p>
<span class="custom_radio">
<input type="radio" id="featured-1" name="s_radio" value="1"> <label for="featured-1">item 1</label>
</span>
</p>
</div>
<span id="add" class="btn btn-sm btn-primary">add</span>
<span id="remove" class="btn btn-sm btn-pub">remove</span>
So your JS code is complicity unnecessary as HTML will do this for you alone... And it was clearly stated in comments.
You are adding your JS click event listener on page load and it creates a list of elements on page load. You are adding more of them with button and they will not be included in that list. So solution is to bound listener on document itself and when clicked it will check for all elements with added selector.
So do not use $("[name='s_radio']").on("click", function() { where you target just already loaded [name='s_radio'] radios
Use $("document").on("click", "[name='s_radio']", function() { where you will bind document and on click it will check for all [name='s_radio'], new or old. By new I talk about dynamically added with button.
So people do not have problems with radio buttons, Id say radios have problem with some people. And browser IS your friend. You just need to learn to use it.
This should solve the problem
$(document).on('click',"[name='s_radio']",function (e) {
$("[name='s_radio']").attr("checked", false);
$(this).attr("checked", true);
})
Related
I am trying to get respective values of dynamically generated inputs. In other words, I have an X number of dynamically generated inputs; each of these inputs is bound to a button. With that being said, I would like the user to get alerted the dynamically generated input that is bound to the clicked button. What I have done so far does not sort this out and whatever button is clicked, only the first input's value is generated.
I have the following code - a dynamic input and a button:
<input type="hidden" id="job_id" name="jobIdName" value="{{ job_id }}"> // please note this input is dynamically generated....
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
As for Jquery, I have done the following:
$('#get_id_id').each(function(index) {
$(this).click(function() {
var job_ids = $("[name='jobIdName']");
console.log('Job Ids -------------- : ' + job_ids);
});
});
The above code keeps generating only the first generated input value? Any ideas or suggestions?
I have seen some posts that might seem similar to this one but they are very old; also I am looking for a more modern implementation.
Add your "input tag" into div:
var counter = 0;
$(document).ready(function(){
$("#get_id_id").click(function() {
var divChildren = $(".job_ids").children();
if(counter < divChildren.length){
if(counter == '0'){
console.log($(divChildren).eq(0).val());
}else{
console.log($(divChildren).eq(counter).val());
}
counter++;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="job_ids">
<input type="hidden" name="jobIdName" value="Test01">
<input type="hidden" name="jobIdName" value="Test02">
<input type="hidden" name="jobIdName" value="Test03">
<input type="hidden" name="jobIdName" value="Test04">
<input type="hidden" name="jobIdName" value="Test05">
</div>
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.
I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:
var clicks = 0;
function clickME() {
clicks += 1;
if (clicks == 2) {
clicks = 0;
}
document.getElementById("clicks").innerHTML = clicks;
}
<input type="Button" id="bt" />
Considering each button (or more generically each element) is part of the DOM (Document Object Model), each one is an object, so no one makes you unable to use them: you can set the field clicks for each button DOM object:
function clickME(event) {
var btn = event.target;
btn.clicks = ((btn.clicks || 0) + 1) % 2;
window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
document.getElementById("clicks").innerText = window.clicks;
}
Checking out your code, I also simplified your logic replacing the if to check zero with the MOD (%) operator. Furthermore I replaced innerHTML with innerText because the number we won't to be rendered as HTML code, but as plain text, although in this case, it doesn't make difference.
Note:
Don't forget to pass the event data object with the onclick attribute in HTML:
<input onclick="clickME(event)" ...>
Check out this fiddle:
https://jsfiddle.net/57js0ps7/2/
You need to maintain a counter per each button individually - use an array to keep track of how many times a button has been clicked. If you don't the clicks var in your code will be two when you select 2 buttons and reset.
On your html:
lets say you have 50 of these
<button type="button" data-clicked="false">1</button>
<button type="button" data-clicked="false">2</button>
and on your javascript
var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
if (this.dataset.clicked == 'false') {
this.dataset.clicked = 'true';
this.innerHTML = parseInt(this.innerHTML) + 1;
}
else {
this.dataset.clicked = 'false'
this.innerHTML = parseInt(this.innerHTML) - 1;
}
})
});
EDIT: Here is a working fiddle
Since you have this tagged as jQuery here is a solution using jQuery. The solution involves using the data- attribute to hold the click count for each button (input). Not sure why you use inputs instead of buttons, but I kept that the same
It also has a getTotal() function that goes through each element and tallies the click to see how many slots were selected and displays that number for you.
$(document).ready(function() {
$(".btn").on("click", clickME);
});
function clickME() {
var clicks = $(this).data("clicks");
var newClicks = parseInt(clicks) + 1;
if(newClicks > 1){
newClicks = 0;
}
// set the new click count on the element
$(this).data("clicks", newClicks);
setTotal();
}
function setTotal(){
var total = 0;
$(".btn").each(function(imdex, btn) {
var currClicks = parseInt($(btn).data("clicks"));
total += currClicks;
});
$("#clicks").text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Button" class="btn" data-clicks=0 value="0" />
<input type="Button" class="btn" data-clicks=0 value="1" />
<input type="Button" class="btn" data-clicks=0 value="2" />
<input type="Button" class="btn" data-clicks=0 value="3" />
<input type="Button" class="btn" data-clicks=0 value="4" />
<input type="Button" class="btn" data-clicks=0 value="5" />
<input type="Button" class="btn" data-clicks=0 value="6" />
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>
I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.
I'm trying to save the .addClass every time I save a stylesheet so that the button remembers
The user can toggle the option on/off.
My simple html:
<div id="btn-switch" class="btn-group" data-toggle="buttons">
<button class="btn btn-default" type="radio" name="options" id="option1" data-color="{T_THEME_PATH}/normal.css" autocomplete="off">off</button>
<button class="btn btn-default" type="radio" name="options" id="option2" data-color="{T_THEME_PATH}/inverse.css" autocomplete="off">on</button>
</div>
This is my code:
<script>
$(document).ready(function() {
if ($.cookie("css")) {
$("#bg").attr("href", $.cookie("css"));
}
$("#btn-switch button").click(function() {
$("#bg").attr("href", $(this).attr('data-color'));
$("#btn-switch .active").removeClass("active");
$(this).addClass("active");
$.cookie("css", $(this).attr('data-color'), {
expires: 365,
path: '/'
});
return false;
});
});
</script>
How can use the same cookie to save the .active class?
I would also use local storage for all of this but I dont know how to even start the code snippet I achieved above
Here is a way to use localstorage:
Given this markup (I am using input type="radio" for this example):
<div class="btn-group" data-toggle="buttons" id="btn-switch">
<label class="btn btn-default">
<input type="radio" id="option1" name="options" value="1" data-color="{T_THEME_PATH}/normal.css" autocomplete="off"> off
</label>
<label class="btn btn-default">
<input type="radio" id="option2" name="options" value="2" data-color="{T_THEME_PATH}/inverse.css" autocomplete="off"> on
</label>
</div>
<br><br>
<a id="bg" href="{T_THEME_PATH}/normal.css">Background</a>
In the script, listen for the change event on the radio buttons. This is fired for any radio that is checked. First set the #bg href to the clicked radio's color data-attribute (Use jQuery .data()). Then store this href to localstorage. Additionally store the ID of the clicked option to localstorage. Then on subsequent page loads use the items in localstorage to set the correct href and activate the correct radio button:
$(document).ready(function() {
var csshref = localStorage["css"];
if (csshref) {
$("#bg").prop("href", csshref);
}
var activeid = localStorage["activeid"];
if (activeid) {
$("#" + activeid).prop("checked", true).closest("label").addClass("active");
}
$('#btn-switch [type="radio"]').on("change", function() {
$("#bg").attr("href", $(this).data('color'));
localStorage.setItem('css', $(this).data('color'));
localStorage.setItem('activeid', $(this).prop('id'));
return false;
});
});
Here is a DEMO
In the demo, try checking on and off and then hittin RUN again. You will see that subsequent runs remember which item was checked and set the href appropriately.
Here is a simple way to do it:
$(document).ready(function () {
//on page load check for cookie value and add active class
if($.cookie("isButtonActive") == 1)
{
$("#btn-switch button").addClass("active");
}
$("#btn-switch button").click(function() {
//your previous code here
if($("#btn-swtich button").hasClass("active") == true)
{
//button was active, de-activate it and update cookie
$.("#btn-switch button").removeClass("active");
$.cookie("isButtonActive", "0");
}
else
{
//button is not active. add active class and update cookie.
$.("#btn-switch button").addClass("active");
$.cookie("isButtonActive", "1");
}
});
});
I have a webpage. There is a button called add. When this add button is clicked then 1 text box must be added. This should happen at client side only.
I want to allow the user to add at most 10 text boxes.
How can I achieve it using javascript?
example:
only 1 text box is displayed
user click add >
2 text boxes displayed
user clicks add >
I also wants to provide a button called "remove" by which the user can remove the extra text box
Can anyone provide me a javascript code for this??
Untested, but this should work (assuming an element with the right id exists);
var add_input = function () {
var count = 0;
return function add_input() {
count++;
if (count >= 10) {
return false;
}
var input = document.createElement('input');
input.name = 'generated_input';
document.getElementbyId('inputs_contained').appendChild(input);
}
}();
add_input();
add_input();
add_input();
A solution using the jQuery framework:
<form>
<ul class="addedfields">
<li><input type="text" name="field[]" class="textbox" />
<input type="button" class="removebutton" value="remove"/></li>
</ul>
<input type="button" class="addbutton" value="add"/>
</form>
The jQuery script code:
$(function(){
$(".addbutton").click(){
if(".addedfields").length < 10){
$(".addedfields").append(
'<li><input type="text" name="field[]" class="textbox" />' +
'<input type="button" class="removebutton" value="remove"/></li>'
);
}
}
// live event will automatically be attached to every new remove button
$(".removebutton").live("click",function(){
$(this).parent().remove();
});
});
Note: I did not test the code.
Edit: changed faulty quotation marks
I hope you are using jQuery.
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript"><!--
$(document).ready(function(){
var counter = 2;
$("#add").click(function () {
if(counter==11){
alert("Too many boxes");
return false;
}
$("#textBoxes").html($("#textBoxes").html() + "<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input type='textbox' id='t"+counter+"' > </div>\n");
++counter;
});
$("#remove").click(function () {
if(counter==1){
alert("Can u see any boxes");
return false;
}
--counter;
$("#d"+counter).remove();
});
});
// --></script>
</head><body>
<div id='textBoxes'>
<div id='d1' ><label for="t1"> Textbox 1</label><input type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>