jQuery trigger event on multiple fields with the same classname - javascript

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">

Related

I want to display the text when you hit enter using IIFE

I have a text box that takes input and when i hit enter it stores the output and displays in an unordered list format. The function without IIFE works when i use onclick event. However, with IIFE its not functioning. Please help.
<html>
<head>
<title>messagewithenter</title>
</head>
<body>
Message:
<input type="text" name="message" id="message">
<input type="submit" value="add" id="submitenter" style="display: none">
<ul id="list"></ul>
<script>
(function () {
var link = document.getElementById("submitenter");
link.addEventListener("click", function () {
document.onkeypress = enter;
function enter(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
});
function addMessage() {
var message = document.getElementById("message").value;
var output = "<li>" + message + "<li" + "<br>";
document.getElementById("list").innerHTML += output;
}
}());
</script>
</body>
</html>
You were binding the event on click event of an invisible element, simply make it
document.onkeypress = enter;
function enter(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
Demo
document.onkeypress = enter;
function enter(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
function addMessage() {
var message = document.getElementById("message").value;
var output = "<li>" + message + "<li" + "<br>";
document.getElementById("list").innerHTML += output;
}
Message:
<input type="text" name="message" id="message">
<input type="submit" value="add" id="submitenter" style="display: none">
<ul id="list"></ul>
link.addEventListener("click", function () {
document.onkeypress = enter;
...
This code is flawed because if it works, it would reset the document.onkeypress event handler every time you click in the input box.
It's also unnecessary, as you can set that onkeypress handler without needing the click event. The whole thing can be written like this:
document.onkeypress = function(e) {
if (e.which == 13 || e.keyCode == 13) {
addMessage();
}
}
No need for the click handler at all.

Unable to manually trigger keydown event with jquery

<form>
<div id="part-inputs">
<div class="part-input">
<label>Part 1</label>
<input type="number" class="start" name="s[0]" value="" placeholder="start time" tabindex="3">
<input type="number" class="finish" name="f[0]" value="" placeholder="finish time" tabindex="4">
</div>
</div>
<input type="submit" name=submit>
</form>
<script>
var nextPartNo = 2;
var template = '<div class="part-input">' +
'<label>Part <%= partNo %></label>' +
'<input type="number" class="start" name="s[<%= partNo -1 %>]" value="" placeholder="start time" tabindex="<%= (partNo-1)*2+1 %>">' +
'<input type="number" class="finish" name="f[<%= partNo -1 %>]" value="" placeholder="finish time" tabindex="<%= (partNo-1)*2+2 %>">' +
'</div>';
var compiledTemplate = _.template(template);
// check for tab keydown at finish field
$("#part-inputs").on('keydown', '.finish', function(event) {
var keyCode = event.keyCode || event.which;
if (keyCode == 9) { // tab key
var $partInputTargeted = $(event.target.parentElement); // div#part-input
if (!$partInputTargeted.is(':last-child')) {
return;
}
$("#part-inputs").append(compiledTemplate({
partNo: nextPartNo
}));
nextPartNo++;
}
});
// check for enter key at both fields
$("#part-inputs").on('keydown', ['.start', '.finish'], function(event) {
var keyCode = event.keyCode || event.which;
if (keyCode == 13) { // enter key
console.log("here"); // this verifies we reach the block where we trigger jquery event
event.preventDefault();
var e = jQuery.Event("keydown");
e.which = e.keyCode = 9; // Create tab key event
$(event.target).trigger(e);
}
});
</script>
Above is a snippet of the dynamic form, I am creating. There are multiple units of a start field and a finish field. Each unit is a div#part-input. All div#part-input divs are children of div#part-inputs.
On tab event triggered at finish field of last div#part-input, a new div#part-input will be appended. I am compiling the template using underscore.js( This working as expected)
Now I want enter key at any of the fields(start or finish) to trigger tab event on the same . This where code is not doing anything.
First of all looks like there is a typo in your submit button, missing the quotes around the name prop.
Try this, it should work for what you are looking for. It will trigger if the enter key is pressed while in a finished input. I took out our template adding to it's own function so you can call it in multiple places.
function addTemplate() {
var $partInputTargeted = $(event.target.parentElement); // div#part-input
if (!$partInputTargeted.is(':last-child')) {
return;
}
console.log('add new template');
}
$("#part-inputs .start, #part-inputs .finish").keydown(function (event) {
if (event.which === 13) {
event.preventDefault();
var index = $('input').index(this) + 1;
$('input').eq(index).focus();
if($(this).attr('class') === 'finish') {
addTemplate();
}
}
});
// check for tab keydown at finish field
$("#part-inputs").on('keydown', '.finish', function(event) {
var keyCode = event.keyCode || event.which;
if (keyCode == 9) { // tab key
addTemplate();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="part-inputs">
<div class="part-input">
<label>Part 1</label>
<input type="number" class="start" name="s[0]" value="" placeholder="start time" tabindex="3">
<input type="number" class="finish" name="f[0]" value="" placeholder="finish time" tabindex="4">
</div>
</div>
<input type="submit" name="submit" />
</form>
If I understand it correctly you want to change focus on next input when user presses enter key. Why don't you directly set the focus with javascript? There is no need to fake keyboard events.
This snippet should help you:
$('input,select').keydown( function(e) { // Add event listener
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 13) { // If enter key
e.preventDefault();
var inputs = {YOUR INPUTS} // $('.YOUR-SEELCTOR-CLASS').find(':input:visible');
var nextinput = 0;
// Find next input
if (inputs.index(this) < (inputs.length-1)) {
nextinput = inputs.index(this)+1;
}
// Handle input focus
if (inputs.length==1) {
$(this).blur().focus();
} else {
inputs.eq(nextinput).focus();
}
}
});

Submit form on keypess after verification

$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode === 13){
SearchThis.submit();
return false;
}
});
});
So now my form (SearchThis) is submitted whenever the enter key is pressed which is great however how do I modify it to check if mysearchfied has been completed before it submits?
IE. If mysearchfied is empty and the enter key is pressed don't submit the form. If mysearchfied contains text and the enter key is pressed then submit the form.
Hope you can help! Thanks...
If you just want to validate the textbox for required use HTML5 required attribute like:
<input type="text" class="form-control" name="mysearchfield"
value="" id="mysearchfield" placeholder="Company or SmartPages Category..." autocomplete="off" required>
listenOn = function(domElement) {
domElement.addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
onEnterPressed();
}
});
function onEnterPressed() {
if (validateForm()) {
submitForm();
} else {
alert('Invalid form');
}
}
function validateForm() {
var inputValue = document.getElementById("myInput").value;
return (inputValue.length >= 1);
}
function submitForm() {
var formElement = document.getElementById("myForm");
alert('Submit form');
formElement.submit();
}
}
listenOn(document);
//listenOn(document.getElementById("myForm")); //You could also listen keydowns on form element(sure only if global keypress isn't exactly what you want).
<form id="myForm" action="#send.php">
<input id="myInput" type="text" placeholder="I'm empty now." />
</form>
There are two ways to validate the form.
-> Check is the form valid usind the form valid function
SearchThis.validate().valid()
-> validate each field for value as told by #n01ze
if the id of your input field is mysearchfield, then you could do it like this:
var msf = document.getElementById("mysearchfield").value;
$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode == 13){
if (msf != "") {
SearchThis.submit();
return false;
}
else
{
// some code here....
}
}
});
});
if (event.keyCode === 13) {
if ($('mysearchfied_ID_or_Class').val()!=='') {
//mysearchfied is not empty
SearchThis.submit();
}
else {
//dont submit, do your checks
}
return false;
}

Validating textbox on copy paste in mvc

I have a textbox that has variable maxlenght based on some condition. There are keyup and keydown events associated with the textbox. On paste my maxlenght validation fails.If "Location" is selected the type of textbox is number with maxlenght 6, for other the type is text with maxlen 11 and 15 respectively "
$(document).on("pageinit", function (event) {
$('input[type="text"]').on('keyup keydown', function (event) { /*Some validation*/} });
$('input[type="number"]').on('keyup keydown', function (event) { /*Some validation*/} });
JQuery
$(document).ready(function() {
var characters ;
$("#text").keyup(function(){
if($('#vehicle').prop('checked')){
characters=5;
}
else{
characters=10;
}
if($(this).val().length > characters){
$(this).val($(this).val().substr(0, characters));
}
});
});
HTML
<input type="checkbox" id="vehicle" value="Bike">I have a bike<br>
<input type="text" id="text"/>
SEE DEMO HERE
I used paste event to trigger keyup event because only using paste event I can somehow get the input but I couldn't manipulate the input given. Here's how I found a way -
$(".AlphaValidateOnPaste").on('paste', function(e) {
$(e.target).keyup();
});
$('.AlphaValidateOnPaste').on('keyup',function(e){
var value = $(this).val();
var i = value.length;
while (i--) {
var result = value.charAt(i).match(/^[a-zA-Z ]*$/);
if(result == null){
$(this).val('');
alert('Only Alphabates and Spaces');
break;
}
}
});
<label for="name">Name <span class="required">*</span></label>
<input type="text" name="employee_name" class="form-control AlphaValidateOnPaste" id="employee_name" required>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

i want alert some thing every time when i pressed enter key

every time time when i pressed the enter key in input field then it should alert some thing but facing problem in doing that here is the code.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(this.value)">
Here is the js code
<script>
function ajxsrch(str)
{
var keycod;
if(window.event)
{
keycod = str.getAscii();
}
if(keycod==13){alert("You pressed Enter");}
}
</script>
I think it is because you aren't passing e to the function and only using window.event which does not work in all browsers. Try this code instead.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)">
<script>
function ajxsrch(e)
{
e = e||event;
var keycod;
if(e)
{
keycod = e.keyCode||e.which;
}
if(keycod==13){alert("You pressed Enter");}
}
document.getElementById("input").onkeyup=ajxsrch;
</script>
Try this..
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(event)">
<script>
function ajxsrch(e)
{
if (e.which === 13) {
alert("You pressed Enter");
}
return false;
}
</script>
Pass the event object to the function call
<input type="text" class="searchfld" id='input' onkeyup="ajxsrch(event)">
Use the event object in the JS and get the key value.
function ajxsrch(ev) {
var ch = ev.keyCode || ev.which || ev.charCode; // Proper way of getting the key value
if(ch == 13) {
alert("You pressed enter");
}
}

Categories