How to properly register a click event on a radio button? - javascript

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>

Related

Want to add delete functions for a list of date displayed

to summarize my problem ... I have made a calendar with contains the from - to date range. Now the selected dates are displayed in a div with a delete button for each. But as the id of the button is the same for all the dates ....it deletes the entire date range. I have attached the screenshot as well.
I also tried taking a loop and giving each date a div so that the Del function will work properly. but I wasn't successful. I will mention code for the same
$(document).ready(function () {
var i = 0;
$.each(between, function (key, value) {
var rest = $('#target').append($('<div id="r' + i +value+ '" class="ansbox">
</div>'));
console.log(between);
var template = '<div id="ChildTarget_' + i + '"><span>key + ":" + "' + value + '"
</span><button id="tr' + i + '" class="target">X</button></div><br></div>';
i++;
$('#target').on('click', function () {
console.log("hola");
$('#target').remove();
You should add click event for the button itself.
var template = `
<div id="ChildTarget_' + i + '">
<span>key + ":" + "' + value + '"</span>
<button id="tr' + i + '" class="deleteButton">X</button>
</div>`;
$(".deleteButton').on('click', function() {
// do deletion here
});
First of all ,
The 'X' button should have different id
$.each(between, function (key, value){
$('#results').append(key+":"+value+'<br>');
$('#results').html(between.join('<button id="result"+key+"" > X </button><br>')
here you can see i am adding key to the Button Id making it unique. Use that id to remove the value, that you dont want. Hope this helps

jQuery remove an element if radio button is not checked

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;

Onclick event are not working properly

on click event in node.js is not working but simple text input work.i want that when you click on buttons( in my case two buttons) the two different event happen but it does not work. these two different events are append DOM within page. one of the button have value 'X' and other one have 'O' and i want to just append DOM with button's value. How can i do that?
this is code--->
my script is-
$(function() {
var socket = io.connect(window.location.href);
socket.on('message:server', function(data) {
$("#messages").append(
'<li style="color:red">' +
data.message + ' - ' + 'received' + ' ' + new Date() +
'</li>'
);
});
$("#message_form").on('submit', function(event) {
event.preventDefault();
var $input = $('[name="message"]')
var message = $input.val();
if (message) {
socket.emit('message:client', {message: message});
}
$("#messages").append(
'<li style="color:green">' +
message + ' - ' + 'sent' + ' ' + new Date() +
'</li>'
);
$input.val('');
});
socket.on('error', function() {
console.error(arguments)
});
});
in Body tag-
<form id="message_form" method="post">
<input name="message" placeholder="Message to send" type="text"/>
<button type="submit">Submit</button>
</form>
here at bottom in place of form i want 2 buttons which can operate this with default given fix value.
What about creating two buttons in the DOM and calling .on('click', function(){}) instead of submit ?
Like :
<button id="value1">Send value 1</button>
<button id="value2">Send value 2</button>
Then you simply set the function on click event. I added comments to your code to show what you can remove :
$("#value1").on('click', function(event) {
event.preventDefault();
// var $input = $('[name="message"]');
// You don't need fix since you send "fixed" value
var message = "Value 1" // Or whatever you want instead of $input.val();
// if (message) {
// No need of condition since you set the value
socket.emit('message:client', {message: message});
// }
$("#messages").append(
'<li style="color:green">' +
message + ' - ' + 'sent' + ' ' + new Date() +
'</li>'
);
// $input.val('');
});
You simply do the same for your button 2.
For this example, you would call :
$('#value2').on('click', function(){
// Same as value with another message value
});

Click function not registering correctly in Jquery

I have a function that should be triggered on click of productid...
$("[id^='productid']").click(function(){
var numberPattern = /\d+/g;
match = this.id.match(numberPattern)
})
The products are generated using Jquery pagination as given below....
function createproducts(jsondata){
transactiondata = jsondata
$("<div id='product-container'></div>").appendTo("#product-list");
$('#pagination').pagination({
items: jsondata.length
,itemsOnPage: 12
,onInit:redrawData
,onPageClick: redrawData
,cssStyle: 'light-theme'});
}
function redrawData(pageNumber,event){
if (pageNumber) {
slicedata = transactiondata.slice(pageNumber*12,
Math.min((pageNumber+1)*12,transactiondata.length));
}
else {
slicedata = transactiondata.slice(0,12)
}
$("#product-container").empty()
slicedata.forEach(function(e,i,a){
var obj = e;
$("<div id = productid" + i + " class = product-cards </div>").appendTo('#product-container')
//-working$("<div id='product" + i + "left' class='product-cards-left' style='background-image:url( " + imagepath_start + obj.image_caption + ")'> </div>").appendTo('#product' + i);
//lightbox is the jquery plugin that we use..The below line is very sensitive...
//-lightbox working$(" <div id='product" + i + "left' class='product-cards-left' style='background-image:url( " + imagepath_start + obj.image_caption + ")' > </div>").appendTo('#product' + i);
$("<div id='product" + i + "left' class='product-cards-left' style='background-image:url( " + imagepath_start + obj.image_caption + ")'> </div>").appendTo('#productid' + i);
$("<div id = product" + i + "right class = product-cards-right> </div>").appendTo('#productid' + i )
$("<label><b> Price: <b></label> <label>" + '$' + obj.price + "</label><br>").appendTo('#product' + i +"right" )
$("<label><b> Old Price: <b></label> <label>" + '$' + obj.old_price + "</label><br>").appendTo('#product' + i +"right" )
$("<label><b> Author Name: <b></label> <label>" + obj.author_name + "</label>").appendTo('#product' + i +"right" )
$("<div id= elementid style='display:none' >"+ obj.id+" </div>").appendTo('#product' + i +"right" )
//$("<label>" + obj.name + "</label>").appendTo('#product' + i +"right" )
})
Problem:-
When I click the productid the click function is correctly working and calculates "match" correctly..But once I move to next page(Onpageclick is triggered) and click productid, the click function is not working anymore..Why would this happen?
You can use $(document) handler so that your click handler is not lost.
$(document).on("click", "[id^='productid']", function(){
var numberPattern = /\d+/g;
match = this.id.match(numberPattern)
});
You need to use a delegated event handler like this:
$(document).on("click", "[id^='productid']", function(){
var numberPattern = /\d+/g;
match = this.id.match(numberPattern)
});
It works by listening for events bubbled up to a non-changing ancestor element, then applying the jQuery selector on the chain of elements that caused the event, then applies the function to any matching elements that caused the event.
You would normally attached the delegated event to the nearest non-changing ancestor element, but the fallback is document if nothing is convenient to use. Do not ever use body for delegated events as it has a bug with some events (due to styling).
When you change the page you lose the hook jquery adds on the DOM which is triggering the click. Just recall the method that listens to clicks on page change.

Jquery reading input field that was created from JSON loop

I cannot figure out for the life of me why this will not work. I am trying to pull the value of a textfield that was created with a loop from a json file.
In this code, at the very bottom I just do a simple click(function() {alert()} just to see if I can pull a value and its returning undefined. But if I remove '#name' and put in 'input' it captures it, but only for the first of several input fields.
Any help is really appreciated
JSON
{
"Controls": [{
"Button":[{ "Name":"Button", "x": "1","y": "2","width": "3","height": "4","Transition":"" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12","Rows":""}]
}]
}
The Code(there is soome getJSON stuff above this)
//Slide In Attributes Panel Based on Selected Object
$(document).on('click', '#code li', function () {
var index = $('#code li').index(this);
var selected = $(this).text();
switch (selected) {
case selected:
$('#options').hide();
hidePanels();
$('#temp').remove();
$('#objectAttributes').show("slide", 200);
break;
//If it does work show what variable is being used
default:
alert(selected);
break;
}
//Shows Selected LI Index
$('#codeIndex').text("That was div index #" + index);
//Pull list of Attributes for selected Object
$.getJSON('controls.json', function (data) {
//Build Attributes List
var attributeList = '<div id="temp">';
//Target based on selected object
var target = selected;
attributeList += '<div>' + target + '<div>';
$.each(data.Controls[0][target][0], function (kk, vv) {
attributeList += '<div style="float:right">' + kk + ':' + '<input type="text" id='+ kk + '>' + '</input>' + '</div>';
});
attributeList += '</div></div>';
attributeList += '</div>';
$('#objectAttributes').append(attributeList);
$('#temp').append('<div id="editIndex">'+"Modifying index" + " " +index+'</div>');
$(document).on('click', '#saveAttributes', function () {
var $x = $('#name').val();
alert($x);
})
});
});
Ok, so after a little hacking around with a jsfiddle the answer turned out to be a lot simpler than I first thought. Ever since HTML 4.01 class names and IDs have been case sensitive (reference), which means that your selector $('#name') wasn't matching the JSON Name.
So a simple change, such as in this simplified jsfiddle seems to work as desired. Hopefully this helps!

Categories

Resources