How can i make an event fire every time on button click - javascript

im trying to make and the same event fire every time but it only fires once when i click "del" button
HTML
<input type="text" name="todoInput" id="todoInput">
<button class="btn">Add</button><br>
<p class="error"></p>
<div>
<ul class="todos"></ul>
</div>
jQuery
var todos = [];
$(".btn").click(function() {
if ($("#todoInput").val().length != 0) {
todos.push($("#todoInput").val());
$("#todoInput").val("");
console.log("Novi array:", todos);
$(".todos").html("");
$(todos).each(function(index, val) {
$(".todos").append(`<li value=${val}>${val}<button class="del" value=${index}>del</button></li>`);
});
**$(".del").click(function() {
todos.splice($(this).val(), 1);
$(".todos").html("");
$(todos).each(function(index, val) {
$(".todos").append(`<li value=${val}>${val}<button class="del" value=${index}>del</button></li>`);
});**
});
} else {
$(".error").text("Molimo unesite vrijednost.");
console.log("Trenutni array:" ,todos);
}
});
$("#todoInput").on("input", function() {
if ($("#todoInput").val().length != 0 && $(".error").text("Molimo unesite vrijednost.")) {
$(".error").text("");
}
});
im trying to make and the same event fire every time but it only fires once when i click "del" button

The issie you have is that the (".del").click(function() { function is not running repeatedly and therefore not binding the onclick handler to it.
Perhaps an alternative method would be to create the delete function and pass in the the index of the item to delete, see below snippet:
let todos = [];
function buildItems() {
if (todos.length > 0) {
$(".todos").html("");
$(todos).each(function(index, val) {
$(".todos").append(`<li value=${val}>${val}<button class="del" onclick="deleteItem(${index});" value=${index}>del</button></li>`);
})
} else {
$(".todos").html("");
}
}
function deleteItem(index) {
todos.splice(index, 1);
buildItems();
}
$(".btn").click(function() {
if ($("#todoInput").val().length != 0) {
todos.push($("#todoInput").val());
$("#todoInput").val("");
// console.log("Novi array:", todos);
buildItems()
} else {
$(".error").text("Molimo unesite vrijednost.");
console.log("Trenutni array:", todos);
}
});
$("#todoInput").on("input", function() {
if ($("#todoInput").val().length != 0 && $(".error").text("Molimo unesite vrijednost.")) {
$(".error").text("");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="todoInput" id="todoInput">
<button class="btn">Add</button><br>
<p class="error"></p>
<div>
<ul class="todos"></ul>
</div>

We actually use on/off click to make sure the click triggers the event.
$(".btn").off ('click').on('click',function() {...}

Related

jQuery trigger event on multiple fields with the same classname

I have multiple input fields that have the same class name, such as:
<input type="text" class="input-name" value="John">
<input type="text" class="input-name" value="Maria">
When someone presses ENTER in any field, the text !!! is automatically appended to the value. This works great.
$(document).on('keypress', '.input-name', function(event)
{
if (event.which != 13)
return;
$(this).val($(this).val() + '!!!');
});
The problem is that I'd like to press a button and change the value of all fields, by simulating the ENTER keypress event and for some reason, it only triggers in the first input!
This only triggers in the first input:
var e = $.Event('keypress', { which: 13 });
$('.input-name').trigger(e);
This also only triggers in the first input:
$('.input-name').each(function(i, input)
{
$(input).trigger(e);
});
You can see the problem in this JSFiddle.
Define jquery Event object inside the each function callback as follows.
$('.input-name').each(function (i, input) {
var e = $.Event('keypress', {
which: 13
});
$(input).trigger(e);
});
I would just make a function that does the work and not deal with event handlers
//function alterInps(inps) {
// inps.val(function () { return this.value + "!!!"; });
//}
function alterInps(inps) {
var re = /!!!$/;
inps.val(function () {
return this.value + (re.test(this.value) ? '' : '!!!');
});
}
$(document).on('keypress', '.input-name', function(event) {
if (event.which != 13) return;
alterInps($(this));
});
$('button').on("click", function () {
alterInps($('.input-name'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input-name" value="John">
<input type="text" class="input-name" value="Maria">
<button type="buton">All</button>
$('.input-name').on('keypress', function(event)
{
if (event.which != 13)
return;
$(this).val($(this).val() + '!!!');
});
$(document).on('click', '#btn-submit', function()
{
var e = $.Event('keypress', { which: 13 });
//$('.input-name').trigger(e);
$('.input-name').each(function(i, input)
{
$(input).trigger(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn-submit">
Click me
</button>
<input type="text" class="input-name" value="Maria">
<input type="text" class="input-name" value="John">

Datepicker Date control does not disappear when I click outside Angular 4

When i press the Date control,
and i do not enter a date,
I click Esc ==> The Date control does not disappear
I click outside ==> The Date control does not disappear
here my code html and ts :
<input class="cssInputDate" type="text" id="dateDebut" name="dateDebut"
#dateDebut="ngModel"
(keyup)="onKeyUp($event)"
(blur)="checkDateDebut()"
required [ngModel]="dateDebutModel" (ngModelChange)="dateDebChange($event)" ngbDatepicker #ddeb="ngbDatepicker" >
<button tabindex="3" (click)="ddeb.toggle(); openDatepicker(ddeb)" type="button" style="margin-left: 0;" *ngIf="modificationMode" >
<i class="fa fa-calendar" aria-hidden="true"></i>
</button>
here the .ts :
openDatepicker(id){
console.log(" id =",id);
console.log(" dateDebInput =",this.dateDebInput);
this.dynamicId = id;
}
onClick(event) {
if(this.dynamicId == undefined){
console.log("Dynamic id ===",this.dynamicId);
}
else if(!this._eref.nativeElement.contains(event.target)) {
this.dateDebInput.close();
}
}
here the console log output :
any solution ?
i find a solution
i use #HostListener here the code :
#HostListener('mousedown', ['$event'])
mouseEvent(event) {
if(event.target.offsetParent.tagName !== 'NGB-DATEPICKER'){
this.dateDebInput.close();
}
}
same of escape :
#HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
if (event.key === "Escape") {
this.dateDebInput.close();
}
}
ere the code of checkDateDebut :
checkDateDebut() {
const check = this.dateDebutModel != null && this.dateDebutModel !== '';
const checkFinAfterDebut = this.checkDateFinAfterDateDebut();
if (!check) {
this.pushMessageFront('DIAG_ERR_029');
} else {
this.spliceMessageFront('DIAG_ERR_029');
}
if (!check || !checkFinAfterDebut) {
this.highlight('dateDebut', true);
} else {
this.highlight('dateDebut', false);
}
return check && checkFinAfterDebut;
}
the css :
.cssInputDate{
min-width: 85px;
}

How to make javascript toggle button?

I have this code but it doesn't work:
HTML:
<button id="btn_search">Search</button>
<input id="srh" type="search">
JS:
var btnSearch = document.getElementById("btn_search");
var search = document.getElementById("srh");
if (document.addEventListener) {
btnSeach.addEventListener('click',activeSearch);
} else if (document.attackEvent) {
btnSearch.attackEvent('onclick',activeSearch);
}
function activeSearch (event) {
event.preventDefault();
if (search.style.width == '0') {
search.style.width = '14.8em';
search.style.opacity = '1';
} else if (search.style.width == '14.8em') {
search.style.width = '0';
search.style.opacity = '0';
}
I need a toggle button
What should I do?
I might think about using a CSS class and toggle() to show/hide you element.
var btnSearch = document.getElementById("btn_search");
btnSearch.addEventListener('click', function(event){
var search = document.getElementById("srh");
search.classList.toggle("hidden");
event.preventDefault();
});
#srh { width: 14.8em; }
#srh.hidden { display: none; }
<button id="btn_search">Search</button>
<input id="srh" type="search" />
You can simply use JQuery to simplify all the proccess. Make all the code as simple as:
function magictoggle(a) {
if (a == 1) {
$("#btn1").attr("onclick", "magictoggle(0)");
$("#searchbox").hide(1000);
//1000 Are the miliseconds will take the box to hide
} else {
$("#btn1").attr("onclick", "magictoggle(1)");
$("#searchbox").show(1000);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn1" onclick="magictoggle(1)">Search</button>
<input type="text" id="searchbox" placeholder="A search Box">

Make sure checkbox is checked before submitting form?

I have a simple "terms of use" checkbox set up and I want users to check it before submitting the form. I'm using the WordPress plugin "WP-Polls".
Here's what I've tried:
$('.wp-polls-form').submit(function() {
if ($('input:checkbox', this).is(':checked')) {
// everything is fine...
} else {
alert('Please agree to the Terms of Use.');
return false;
}
});
The HTML:
<form id="polls_form_1" class="wp-polls-form" action="/index.php" method="post">
<p style="display: none;"><input type="hidden" id="poll_1_nonce" name="wp-polls-nonce" value="12a6404147"></p>
<p style="display: none;"><input type="hidden" name="poll_id" value="1"></p>
<div id="polls-1-ans">
<ul>
<li><input type="radio" id="poll-answer-1" name="poll_1" value="1"></li>
<li><input type="radio" id="poll-answer-2" name="poll_1" value="2"></li>
<li><input type="radio" id="poll-answer-3" name="poll_1" value="3"></li>
</ul>
<label class="check-terms"><input type="checkbox">I am over 18 and I have read and understand the Terms of Use</label>
<input type="button" name="vote" value="Vote" class="Buttons" onclick="poll_vote(1);">
Edit 1:
Updated it to this to include radio buttons:
//Make sure checkbox and radio are checked before submitting
$('.wp-polls-form').submit(function() {
if ($('input:checkbox', this).is(':checked') &&
$('input:radio', this).is(':checked')) {
// everything is fine...
} else {
alert('Please agree to the Terms of Use.');
return false;
}
});
Edit: 2
Thanks to #AnthonyGarcia. The buttons work exactly how I'd like them to, but the only problem is that the form does not submit.
For the submit button, I changed the type from button to submit and also got rid of onclick="poll_vote(1);".
<input type="submit" name="vote" value="Vote" class="Buttons" />
$(function() {
window.poll_vote = function(num) {
console.log(num);
}
$('.wp-polls-form').submit(function(e) {
if (!$('input:radio', this).is(':checked')) {
alert('Please pick a beat.');
return false;
}
if (!$('input:checkbox', this).is(':checked')) {
alert('Please agree to the Terms of Use.');
return false;
}
poll_vote(1);
return false;
});
});
The live site can be seen here. The relevant section is the dark voting section on top.
Edit: 3
Here is the function for poll_vote(). I got it from the polls-js.dev.js file in the plugin here: https://github.com/lesterchan/wp-polls
// When User Vote For Poll
function poll_vote(current_poll_id) {
jQuery(document).ready(function($) {
if(!is_being_voted) {
set_is_being_voted(true);
poll_id = current_poll_id;
poll_answer_id = '';
poll_multiple_ans = 0;
poll_multiple_ans_count = 0;
if($('#poll_multiple_ans_' + poll_id).length) {
poll_multiple_ans = parseInt($('#poll_multiple_ans_' + poll_id).val());
}
$('#polls_form_' + poll_id + ' input:checkbox, #polls_form_' + poll_id + ' input:radio, #polls_form_' + poll_id + ' option').each(function(i){
if ($(this).is(':checked') || $(this).is(':selected')) {
if(poll_multiple_ans > 0) {
poll_answer_id = $(this).val() + ',' + poll_answer_id;
poll_multiple_ans_count++;
} else {
poll_answer_id = parseInt($(this).val());
}
}
});
if(poll_multiple_ans > 0) {
if(poll_multiple_ans_count > 0 && poll_multiple_ans_count <= poll_multiple_ans) {
poll_answer_id = poll_answer_id.substring(0, (poll_answer_id.length-1));
poll_process();
} else if(poll_multiple_ans_count == 0) {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
} else {
set_is_being_voted(false);
alert(pollsL10n.text_multiple + ' ' + poll_multiple_ans);
}
} else {
if(poll_answer_id > 0) {
poll_process();
} else {
set_is_being_voted(false);
alert(pollsL10n.text_valid);
}
}
} else {
alert(pollsL10n.text_wait);
}
});
}
How about this? Hope it helps. Thanks
$('.wp-polls-form').submit(function() {
var isCheckboxChecked = $("input[type*='checkbox']").filter(":checked");
if (isCheckboxChecked) {
// everything is fine...
} else {
alert('Please agree to the Terms of Use.');
return false;
}
});
Your code is never called, because you are not submitting your form. You have to replace this:
<input type="button" name="vote" value="Vote" class="Buttons" onclick="poll_vote(1);">
By something like this:
<input type="submit" name="vote" value="Vote" class="Buttons">
Here is a fiddle with the modified code: http://jsfiddle.net/5st235fn/
I love to replace submit buttons with simple buttons and then submit forms programatically (or POSTing their values with ajax). However, your have an onclick="poll_vote(1);" that we don't know what's doing, so this answer will just make a guess.
If there's a poll_vote and you really mean to call it, try adding this to the end
function poll_vote(param) {
... current code ...
if ($('input:checkbox', '.check-terms').is(':checked')) {
$('.wp-polls-form').submit();
} else {
alert('Please agree to the Terms of Use.');
return false;
}
}

Change Text input value on checkbox select

I am trying to input the value of a checkbox into a text input.
Let's say that the input box is empty - you click on the checkbox, and the value assigned to the checbkox is being shown inside the input box.
$('input.lowercase').on('change', function(){
if ( $(this).is(':checked') ) {
$("input.qwer").on("keyup",function () {
$("input.qwer").html($(this).val());
}); } } );
No matter what I do I can't get this to work. Any help?
http://jsfiddle.net/6ycnzrty/
[EDITED] (As per your needs)
Demo on Fiddle
HTML:
<input type="text" class="output" value="" />
<br>
<input type="checkbox" class="qwer" value="qwerty">Input value of this checkbox(qwert)
<br>
<input type="checkbox" class="numbers" value="1234567890">Input value of this checkbox(numbers)
<br>
<input type="checkbox" class="asdfg" value="asdfg">Input value of this checkbox(asdfg)
<br>
<input type="checkbox" class="zxcvb" value="zxcvb">Input value of this checkbox(zxcvb)
JavaScript:
$('input.qwer').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.qwer').val(), ''));
}
});
$('input.numbers').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.numbers').val(), ''));
}
});
$('input.asdfg').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.asdfg').val(), ''));
}
});
$('input.zxcvb').on('change', function () {
if ($(this).is(':checked')) {
$('.output').val($('.output').val() + $(this).val());
} else {
$('.output').val($('.output').val().replace($('.zxcvb').val(), ''));
}
});
Try This :-
$('input.qwer').on('change', function(){
if ( $(this).is(':checked') ) {
$("input.output").val($(this).val());
}
else{ $("input.output").val("123"); }
});
With above code if checkbox is unchecked then textbox having class 'output' will get its initial view i.e '123',if you don't need this functionality then try this :
$('input.qwer').on('change', function(){
if ( $(this).is(':checked') ) {
$("input.output").val($(this).val());
}
});
EDIT :-
DEMO
Try
var $chk = $('input.qwer').on('change', function () {
//if the checkbox is checked and output is empty set the value
if (this.checked && !$output.val()) {
$output.val(this.value)
}
});
var $output = $("input.output").on("change", function () {
//when the value of output is changed as empty and checkbox is checked then set the value to checkbox
if (!this.value && $chk.is(':checked')) {
this.value = $chk.val();
}
});
Demo: Fiddle
$("input.qwer").on("change",function () {
if($(this).is(":checked"))
$("input.output").val($(this).val());
else
$("input.output").val("123");
});
DEMO

Categories