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
});
Related
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've got some troubles with this code.
$('body').on("keypress", ".message", function(e) {
if ( e.keyCode == 13 && $(".message").val().length > 0 ) {
input = $(".message");
// Check for join command.
if (input.val().substr(0, 5) == "/join") {
// Get channel
channel = input.val().substr(7, input.val().length);
// APPEND NEW TAB
$("ul.nav-tabs li").after('<li><a href="#' + channel + '" aria-controls="#' + channel + '" role="tab" data-toggle="tab">#' + channel + '</li>');
$('.tab-content').append('<li class="tab-pane log" role="tab-pane" id="' + channel + '" data-channel="' + channel + '"><div class="Topic">Hej och välkommen till #' + channel + '.</div><ul class="Messages"></ul><input type="text" name="message" id="message" autocomplete="off" class="message sendValue"></li>');
$(".nav-tabs li").children('a').last().click();
}
log('<strong>Du</strong>: ' + input.val());
send( input.val() );
$(".message").val('');
}
});
The keypress event doesn't react on the dynamically added input, I read something about adding the on event after added, because of that this code runs when the dom is loaded.
So my question is: how can I make this so the dynamic inputs works aswell?
You're already using .on so I think it is working properly and that your real problem is this:
input = $(".message");
which you need to change to this:
var input = $(this);
otherwise you'll always be dealing with the first input even if there's multiple on the page. Also you can use inspect element > console to debug these problems easier. For example if you add:
$('body').on("keypress", ".message", function(e) { console.log(e);
to your script you would have seen that the event handler is working fine and that your problem was further down.
(also change $(".message").val(''); to input.val('');)
I have this a button which a user can click on which adds a comment box at the bottom of the page. My button html looks like this:
<input type="button" name="inspection_2895_14045_comment" tabindex="-1" value="+" class="commentBtn" onclick="generateComment('Test', 14045,1, this )">
So as you can see it calls a method called generateComment which looks like this:
function generateComment(name, id, isInspection, button){
//get the current button and hide it
var btn = $("a[name='" + button.name + "'");
btn.hide();//doesn't work
var generatedName = '';
if(isInspection){
generatedName = "comment_" + id;
}
else{
generatedName = "section_" + id;
}
var comment = $('#comments');
var genHtml = '<div class="bigDataDiv">' +
' <label class="commentBoxLabels">' + name + '</label>' +
' x' +
' <textarea rows="4" class="commentBox" name=' + generatedName + ' maxlength="200"></textarea>'
'</div>';
comment.append(genHtml);
$('html,body').animate({
scrollTop: $(".bigDataDiv").offset().top},
'slow');
}
All this method does it hide the button, generate the comment div then scroll to the newly created div. This code worked no problem and used to hide the button but now for some reason it doesn't work and the button still shows up
As neokio pointed out, you forgot the closing ], but you are also selecting an anchor tag, when what you want is an input tag.
var btn = $("input[name='" + button.name + "']");
Since button in your generateComment function is a reference to the button you could just use this to set your btn variable:
var btn = $(button);
Then you don't have to worry about putting strings together to make your selector, or what kind of element the button is. Your hide should work no matter what that way.
You forgot the closing ] ...
var btn = $("a[name='" + button.name + "']");
You're also missing a + before the final '</div>';
My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable
I have a modal dialog (Bootstrap) that has a list-group with custom list-group-items inside of it (populated by loop using append after adding data from my server).
Inside each list-group-item, I have a Checkbox that will be used to "select" the result. As I populate the items, I hook up the JQuery click event to the respective Checkbox:
// Add to search results
$('#search-results').append(
'<a id="centroid-list-item-' + featureAttrs['ObjectID'] + '" href="\\#"' + 'class="list-group-item" style="outline: 0">' +
'<table style="background: transparent">' +
'<tr>' +
'<td>' +
'<input id="centroid-checkbox-' + featureAttrs['ObjectID'] + '" type="checkbox" value=""> ' +
'</td>' +
'<td>' +
'<h4 class="list-group-item-heading">' +
featureAttrs['UNIQUEID'] +
'</h4>' +
'<p id="centroid-item-text-' + featureAttrs['ObjectID'] + '"' + 'class="list-group-item-text">' +
featureAttrs['NAME'] +
'</p>' +
'</td>' +
'</tr>' +
'</table>' +
'</a>'
);
// When the DOM is ready, add event
$(document).ready(function () {
$('#centroid-checkbox-' + featureAttrs['ObjectID']).click(function (event) {
var objectId = $(this).attr('id').replace(/^\D+/g, '');
console.log(objectId + " was clicked");
if ($(this).is(':checked')) {
// Enable the 'Set Target' button
$('#btn-set-target').removeAttr('disabled');
// Disable all other choices
$('[id^="centroid-checkbox-"]').each(function (event) {
console.log("Picked up values for checkboxes");
if ($(this).attr('id') != ('centroid-checkbox-' + objectId)) {
$(this).attr('disabled', true);
}
});
}
else {
$('#btn-set-target').attr('disabled', 'disabled');
// Enable all text boxes
$('[id^="centroid-checkbox-"]').each(function () {
if (this.attr('id') !== ('centroid-checkbox-' + objectId)) {
this.removeAttr('disabled');
}
});
}
});
});
The problem I am having is that when I call $('[id^="centroid-checkbox-"]') it is returning undefined. However, at the time is gets called, there are about 30 "centroid-checkbox-XXXXX" checkboxes. What am I doing wrong here?
The $ function never returns undefined.
But this in the callback you pass to each is an element, not a jQuery object.
Which means you must use this.id instead of this.attr('id') and $(this).removeAttr('disabled') instead of this.removeAttr('disabled') (and you probably want this.disabled=false or $(this).prop('disabled', false)).
objectId never gets defined because you need to quote enclose the regular expression you're using for replace():
var objectId = $(this).attr('id').replace(/^\D+/g, '');
should be:
var objectId = $(this).attr('id').replace('/^\D+/g', '');
DEMO: http://jsfiddle.net/4fUvn/8/