I have the following code that append elements to the document if the corresponding radio button is checked. This works fine, however I need a way to remove the elements if the radio button is NOT checked.
Here is what I have so far?
// for each radio button
$('input[type=radio]').each(function(){
// if it is checked
if($(this).is(":checked"))
{
var cur = $(this).val();
// append an input text element only if it does not already exist
if(!$('#characterList input:text').is(function(i,e){ return e.value==cur && e.name=='data['+cur+']'; }))
{
$('#characterList').append('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
}
}
else
{
// otherwise remove element if radio button not checked
$('#characterList').remove('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
}
});
});
The .remove(...) does nothing at all. What am I doing wrong here?
remove() doesn't work like that. You have to provide a selector to select the element you wish to remove. This can be done like so:
$('#characterList').remove('input[value="' + $(this).val() + '"]');
Or, alternatively:
$('#characterList').find('input[value="' + $(this).val() + '"]').remove();
Furthermore, instead of using $(this).is(":checked") and $(this).val(), you can simply use:
if ( this.checked )
And:
var cur = this.value;
Related
I'm selecting multiple values in the dropdown list, based on selected values that need to display below with the checkbox is checked.
For Ex:
Multiple-Dropdown-list_image
below Output, I need to display like this when I selected multiple values:-
My Code:
$(document).ready(function() {
$(document).on('change','#tlist', function(){
$('#tdata').attr('style','display:block;');
var li = '';
$('#tlist').each(function() {
var values = $(this).val() ;
$.each(values, function( index, value ) {
var li = $('<input type="checkbox" class="custom-control-input" name="dfield[]" id="' + value + '" value="' + value + '" checked/><label class="custom-control-label blue" for="' + value + '">' + value + '</label>');
$('#tdata').append(li);
});
});
});
But here I'm getting output like this why? I have selected only 3 values so I need to display only 3 selected values. But it's showing some repeated values
OUTPUT:
I am dynamically creating HTML radio buttons where I am assigning the Id of the input tag to a variable. I want to append a click event handler to these radio buttons using the Id I have assigned. How do I properly use the Id I created to generate a click event? Right now, the event is not being triggered at all.
generateDynamicHTML(function (structure) {
let keys = Object.keys(structure);
keys.forEach(function(key){
let radioButton = $("<input type='radio' name='studentName' id=" + key + "/><label for=" + key + ">" + key + "</label>");
radioButton.appendTo('#studentToggle')
$("#" + key).click(function () {
console.log(key);
})
})
})
I am using the console.log to test if the method was being hit but I am getting empty results. I know the keys are correct because the radio buttons are being created.
Any help would be appreciated.
Thank you.
The problem is that the id added is key/ not key. You should leave a space between " and the closing of the input tag. Or use template literals.
See below
const structure = {
'first': 1,
'second': 2
}
let keys = Object.keys(structure);
keys.forEach(function(key) {
let radioButton = $("<input type='radio' name='studentName' id=" + key + " /><label for=" + key + ">" + key + "</label>");
// or template literals
// let radioButton = $(`<input type='radio' name='studentName' id=${key} /><label for=${key}>${key}</label>`);
radioButton.appendTo('#studentToggle')
$("#" + key).click(function() {
console.log(key);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="studentToggle">
</div>
If you use event delegation, you never have to add extra event handlers to options as long as their parent does not change:
const generateDynamicHTML = function( structure ) {
return Object
.keys( structure )
.map(function( key ) {
return '<input type="radio" name="studentName" id="' + key + '"/><label for="' + key + '">' + key + '</label>';
})
.join( '' );
};
const fields = $( '#student_fields' );
// Add the click handler before any radios
fields.on( 'click', 'input[type="radio"]', function( event ) {
console.log( event.target.id );
});
// Add the radios, the click stil works
fields.append( generateDynamicHTML({
"john": { "age": 21 },
"jane": { "age": 20 }
}));
// Add more radios
fields.append( generateDynamicHTML({
"dave": { "age": 21 },
"joe": { "age": 19 }
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="student_fields">
<legend>Students</legend>
</fieldset>
I have a box with multiple checkboxes. I am selecting checkboxes and with that select I am generating a <span> Value (x) </span> on a different div. Now i want to uncheck the checkbox on click of (x) of that particular checkbox.
Example:
On selecting and deselecting the checkboxes the <span> Value (x) </span> is coming and going. but the inverse is not happening.
.reportbox is the class of the tile(checkbox).
#compareSection is the area where buttons are kept.
Code i am using:
<script type="text/javascript">
$('.reportBox').click(function() {
var selected = $('input[type=checkbox]:checked').map(function(_, el) {
selectedCheckbox = el.id;
var element = "<p class='selectedReport'>"+ $(el).val() + "</p>" + "<span onclick='removeReport(this, selectedCheckbox)' class='badge badge-notify close-badge'>x</span>";
return "<span id='elementPack'>" + element + "</span>";
}).get();
$("#compareSection").html(selected);
})
// this code is for removing the URLs
function removeReport(sender, selectedCheckbox) {
document.getElementById(selectedCheckbox).checked = false;
var div = sender.parentNode;
div.parentNode.removeChild(div);
}
</script>
<script>
$(function() {
$('.reportBox').click(function() {
var selected = $('input[type=checkbox]:checked').map(function(_, el) {
selectedCheckbox = el.id;
var element = '<p class="selectedReport">'+ $(el).val() + '</p>' + '<span data-target-box="'+el.id+'" class="badge badge-notify close-badge">x</span>';
return '<span id="elementPack">' + element + '</span>';
}).get();
$("#compareSection").html(selected);
});
$(document).on('click', 'span[data-target-box]', function(e) {
$('#'+$(this).data('target-box')).prop('checked', false);
$(this).remove();
});
});
</script>
On the line
var element = "<p class='selectedReport'>"+ $(el).val() + "</p>" + "<span onclick='removeReport(this, selectedCheckbox)' class='badge badge-notify close-badge'>x</span>";
You are using selectedCheckbox as a string meaning it will look for the variable when you click it, however the variable was never defined outside the first scope. You probably want to change it to the following:
var element = "<p class='selectedReport'>"+ $(el).val() + "</p>" + "<span onclick='removeReport(this, \'"+selectedCheckbox+"\')' class='badge badge-notify close-badge'>x</span>";
So that it calls removeReport(this, 'id_of_element') with the id as a string which can then be used in document.getElementById().
I am dynamically building required components as per css
provided , this way dynamically
for (var i = 0; i < responseinner.length; i++) {
for (var k = 0; k < responseinner[i].type.length; k++) {
random_number += 1;
htmlbuilder.append('<div data-role="collapsible"><h3>' + obj.name + '</h3><div class="prd-items-detials"><ul><li class="head"><form><input type="checkbox" class="checkboxclas" name="checkbox-mini-0" id="' + random_number + '" data-mini="true"><label for="checkbox-mini-0">' + responseinner[i].type[k] + '</label></form></li><li class="prd-items-qt"><div class="col"><i class="minus"></i><i class="qt">1</i><i class="plus"></i></div><div class="col"></div><div id ="' + responseinner[i].type[k] + '" class="col">Rs: ' + responseinner[i].price[k] + '/-</div></li></ul></div></div>');
}
}
Finally . i have registered with the click event for the above generated checkbox .
$(document).on("click", ".checkboxclas", function (e) {
if($(this).is(':checked'))
{
}
});
Is there any way i can access data present at below div
<div id ="' + responseinner[i].type[k] + '" class="col">Rs: ' + responseinner[i].price[k] + '/-</div>
http://jsfiddle.net/PpKpa/
Very Simple Question. Search before posting a question.
Any way, Use Child Selector / Children Method with HTML Method
If you use the change event, which fires when a checkbox or radio button changes from not checked to checked, you do not have to test for if :checked. You are sure if the change event triggered, then the element is checked.
$(function() {
$(document).on("change", ".checkboxclas", function (e) {
//if($(this).is(':checked'))
//{ no need for this if
//YOUR CODE HERE
//}
});
});
i want to append the text box values in the dropdown list when user can change the text box value that time the existing value should be replaced to changed value in the option tag without selected how i can do this
var valuedata
$('.txtbox1').click(function (){
valuedata = $(this).val();
});
$('.txtbox1').focusout(function (){
var data = $(this).val();
if ($('.ddl [value ="' + valuedata + '"]').val() == valuedata) {
alert(valuedata);
$('.ddl').append($("<option value=" + data + " ></option>").html(data).val(data));
}
else {
$(".ddl [value='" + valuedata + "']").val(data);
}
});
Try this :
$('select option:contains("old_text")').text('new_text');
To check for option is appended or not :
$("select option").each(function(i,obj){
if($(obj).text() == "your_text"){
console.log("yes");
}
})
DEMO: http://jsfiddle.net/c2Ry8/
$(document).ready(function() {
$('.txtbox1').focusout(function (){
var data = $(this).val();
$('.ddl').append("<option value=" + data + " >"+data+"</option>");
});
});
There are spaces before [value $(".ddl [value='" + valuedata + "']").val(data); which might be problem. So, remove that space:
$(".ddl[value='" + valuedata + "']").val(data);
Use html instead of append like this:
$('.ddl').html($("<option value=" + data + " ></option>")