I have a search box which should work with pressing the button and also pressing the Enter key. They both have the same code.
The button works perfectly but when it comes to the Enter key, most of the time it doesn't work and sometimes it suddenly works.
Here's my code:
$(document).ready(function() {
function myFunction() {
$("#search-criteria").keydown(function(event) {
if (event.keyCode === 13) {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
}
});
}
$('#search').click(function() {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search-criteria" onkeydown="myFunction()" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
You are adding both an onKeyDown attribute to your HTML and attaching an event listener. So what's happening is that when your key down occurs, it's calling myFunction, which attaches a second event handler for keydown. The second time around the enter key behavior might kick in, but because each keydown attaches a new event listener, you might have the logic kick in multiple times.
Choose one approach or the other. Either use the HTML attribute or add the event listener programmatically, but not both.
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search-criteria" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
JS:
$(document).ready(function() {
$("#search-criteria").keydown(function(event) {
if (event.keyCode === 13) {
doSearch();
event.preventDefault();
}
});
$('#search').click(function() {
doSearch();
});
function doSearch() {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
}
});
(note I also added a .preventDefault() to make sure that the default behavior of the enter key doesn't kick in, since it may submit your form)
Edit:
Moved duplicated code into its own function.
Remove the inline-event onkeydown you don't need it.
You need to use preventDefault inside your myFunction function.
Remove the classes inside your functions to see clearly the new search result.
$(document).ready(function() {
$("#search-criteria").keypress(function(event) {
if (event.which === 13) {
myFunction();
}
});
//code for the button
$('#search').click(myFunction);
});
var myFunction = function() {
event.preventDefault();
var txt = $('#search-criteria').val();
$('.items').removeClass('searched');
$('.items:contains("' + txt + '")').addClass('searched');
}
.searched {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search-criteria" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
<ul>
<li class="items">Coffee</li>
<li class="items">Tea</li>
<li class="items">Milk</li>
<li class="items">Coffee</li>
<li class="items">Tea</li>
<li class="items">Milk</li>
<li class="items">Coffee</li>
<li class="items">Tea</li>
<li class="items">Milk</li>
</ul>
I made a couple of small changes to the code you posted and it is working well for me as a snippet.
I documented the changes in the code itself.
$(document).ready(function() {
//code for Enter key
function myFunction() {
console.log("myFunction called");
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
}
$("#search-criteria").keydown(function(event) {
if (event.keyCode === 13) {
// Keep the ENTER key from submitting the form.
event.preventDefault();
myFunction();
}
});
//code for the button
$('#search').click(function() {
var txt = $('#search-criteria').val();
$('.items:contains("' + txt + '")').addClass('searched');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form>
<!--
the `onkeydown` on this can't work, since 'myfunction' isn't in the global space
so I removed it.
-->
<input type="text" id="search-criteria" name="search" placeholder="Search..">
<input type="button" id="search" value="search" />
</form>
Related
How can I simulate a keypress to an input, using vanilla javascript?
I have tested every possible answer on SO and elsewhere, and it doesn't work on Chrome or Firefox.
For example, let's say we have a form:
<input id="myInput" type="text">
<button id="myButton>Click Me</button>
How could I make it so that when the button is clicked, the letter "a" is added to the input?
You'd first add a keyup event listener to the document object and inside the callback you assign the value of the input via value depending on which key was pressed:
var input = document.getElementById("myInput");
document.addEventListener('keyup', function(e) {
if (e.which === 39 || e.which === 19) {
input.value += 'a';
}
});
<input id="myInput" type="text" />
<button id="myButton">Click Me</button>
This way works i think:
<html>
<body>
<input type="text" id="myText" placeholder=" ">
<button id="but1" onclick="myFunctionA()">A</button>
<button id="but2" onclick="myFunctionB()">B</button>
<script>
function myFunctionA() {
document.getElementById("myText").placeholder = document.getElementById("myText").placeholder + "A";
}
function myFunctionB() {
document.getElementById("myText").placeholder = document.getElementById("myText").placeholder + "B";
}
//And so on
</script>
</body>
</html>
Any doubts tell me
I have a text field and a button. Either when the button is clicked or enter is hit, a function should be executed.
My approach works is intended. However, is it possible to combine those 2 functions (click and keypress), so that I only have 1?
$("button").click(function() {
getInput();
});
$("#name").keypress(function(e) {
if (e.which == 13) {
getInput();
}
});
function getInput() {
alert($("#name").val())
}
So I need to just append those events.
Here is a fiddle.
You can listen for multiple events using .on('listOfEvents')
Than you just need some additional rules to check when you need to run function.
$("button, #name").on('click keypress', function(e) {
if ($(e.currentTarget).attr('id') == 'submit' || e.which == 13) {
getInput();
}
});
function getInput() {
alert($("#name").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" />
<button id="submit">
OK
</button>
function getInput(){
return $(".result").text($("input").val());
}
$("form").on("submit", (ev)=>{
ev.preventDefault();
// handle submission
getInput();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<input type="text" />
<button>ok</button>
</form>
<div class="result"></div>
you can wrap your input and button in a form and listen for a submit event on that form. Forms can be submitted by pressing enter in an input inside of them or clicking a button that is enclosed
HTML
<form action="">
<input type="text" />
<button>ok</button>
</form>
Javascript
$("form").on("submit", (ev)=>{
ev.preventDefault();
// handle submission
getInput();
})
#eltonkamami answer is one idea and my idea is to provide same class for both input field and button like this :
(But, this will trigger whenever input field is changed)
$(".same").bind("click keypress", function() {
getInput();
});
function getInput() {
console.log($("#name").val())
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="name" class="same" />
<button id="submit" class="same">
OK
</button>
Hope it helps :)
We can differentiate a click and keypress by e.key or e.type parameters
Try this,
var getInput = function(e) {
if((e.which & e.which==13) || !e.key)
//e.key is a parameter for keypress event and not for click
alert($("#name").val())
}
$("button").click(getInput);
$("#name").keypress(getInput);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="name" class="same" />
<button id="submit" class="same">
Click
</button>
$("button,#name").on("click keypress",function(e) {
//alert($(e.currentTarget).html());
if (e.which == 13) {
getInput();
}else if(event.type == 'click'){
getInput();
}
});
function getInput() {
alert($("#name").val())
}
I have the following html:
<form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post">
<input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения">
<input type="button" name="addMoney" value="Пополнить" class="btn">
</form>
and following js:
$(function () {
$('#OutSum').keypress(function (e) {
if (e.which == 13) {
alert(2);
return false;
}
});
$("input[name='add-money']").on("click",function(){alert(1);});
});
when I click on button - listener doesn't activate.
What do I wrong ?
JSFIDDLE
change add-money to addMoney in the line $("input.... So it should become:
$("input[name='addMoney']").on("click", function () {
alert(1);
});
Because you gave your input a name of addMoney in your HTML but in your JS, you are trying to access an input with a name of add-money.
Tried to search for this guys sorry. Input in the search box doesnt work (or search) when you hit enter only when the user clicks the search button. What am I doing wrong? Here is my code. Thanks.
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var url = "http://asla.org/awardssearch.html";
url += "?s=" + $('#GoogleCSE').val();
window.location = url;
});
$('#GoogleCSE').keydown(function(event) {
if (event.keyCode == '13') {
$("#submit").click();
}
else {
//do nothing :)
}
});
});
</script>
<form class="navbar-form navbar-right" role="search">
<div class="search">
<input id="GoogleCSE" type="text" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" value="Search All Awards" name="Search All Awards" />
<input id="submit" type="button" value="Search" />
</div>
</form>
If you changed your #submit element's type to "submit", you wouldn't need to manually handle this yourself anyway as this is default browser behaviour:
<input id="submit" type="submit" value="Search" />
Now rather than handling the #submit button's click event, we can instead handle the form element's submit event:
$('form[role="search"]').submit(function() {
var url = "http://asla.org/awardssearch.html";
url += "?s=" + $('#GoogleCSE').val();
window.location = url;
});
JSFiddle demo.
Through $("#submit").click() you're just triggering the click handlers added by yourself, not the controls default behavior when you click on it.
Use yourForm.submit() instead and change the url in its callback:
$("#yourForm").submit(function() {
var url = "http://asla.org/awardssearch.html";
url += "?s=" + $('#GoogleCSE').val();
window.location = url;
});
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'>