Add key eventlistener to last generated input field and stop it after typing - append

When I click a Button, a form of an unspecific number of input fields will be generated in my dom plus an empty input Field.
I want to add something like a keypress event to the last generated empty input field.
When I start typing, into the last empty input field, another input field should append. This new appended input field should get the keypress eventlistener and the input field I am in should loose the keypress eventlistener.
Here's how I did it(EDIT: added as code snippet):
$(document.body).on("input", ".service-input:last", function (e) {
var lastInput = $(".elementCtr.input-ctr input").last(),
inputID = (parseInt(lastInput.attr('name')) + 1);
$("#providerServicesForm .inputs").append('<div class="elementCtr input-ctr"><input id="service_' + inputID + '" type="text" value="" name="' + inputID + '"></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form accept-charset="UTF-8" name="providerServicesForm" id="providerServicesForm" method="post">
<div class="inputs">
<div class="elementCtr input-ctr"><input type="text" name="1" value="test1" id="service_1" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="2" value="test2" id="service_2" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="3" value="test3" id="service_3" class="service-input"></div>
<div class="elementCtr input-ctr"><input type="text" name="3" value="" id="service_3" class="service-input"></div
</div>
</form>
This works fine so far.
But of course I want that this happens only with the first keypress.
After pressing a key, it should stop adding textfields. But when I type something in to the new added (last) textfield it should add a textfield again. But only 1 Textfield after pressing a key etc...
I can't stop the eventlistener after typing.
Does Keypress work with mobile devices?

The great thing about this sort of handler, is if you update the DOM with a new last element, the handler immediately switches to the new element - no need to use .off or .one.
$(document.body).on("input", ".service-input:last", function () {
var inputID = (parseInt($(this).attr('name')) + 1);
$("#providerServicesForm .inputs").append('<div class="elementCtr input-ctr"><input id="service_' + inputID + '" class="service-input" type="text" value="" name="' + inputID + '"></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form accept-charset="UTF-8" name="providerServicesForm" id="providerServicesForm" method="post">
<div class="inputs">
<div class="elementCtr">
<input id="service_0" type="text" class="service-input" value="" name="0">
</div>
<div class="elementCtr">
<input id="service_1" type="text" class="service-input" value="" name="1">
</div>
<div class="elementCtr">
<input id="service_2" type="text" class="service-input" value="" name="2">
</div>
</div>
</form>
One possible enhancement is to detect an empty string and remove the newly added input.

If you only want it to happen for once, why not create a counter and set it to 0. After it had happened, you can increase the counter to 1.
var counter=0;
$(document.body).on("keypress", $(".elementCtr.input-ctr input").last(), function () {
if(counter==0){
//put your logic here
counter++;
}
})

Related

Skip elements within a container when querying DOM

When using querySelectorAll or any DOM query method, I want to skip elements within a given sub-container from querying.
Example:
<div id="container-one">
<div>
<input type="text" name="first">
<input type="text" name="second">
<!-- skip below -->
<div id="container-two">
<input type="text" name="third">
<input type="text" name="fourth">
</div>
<div>
</div>
Suppose in the above case, if you are querying from #container-one element you want to skip elements within #container-two. So the query on #container-one should only return [first, second] elements and skip others (third, fourth).
Appreciate any inputs.
Try this:
document.querySelectorAll('div.container-one')[0].querySelectorAll(':scope > input')
Update(You can't use querySelectorAll for this then):
inputs = document.getElementsByTagName("input");
input_two = document.getElementById('container-two').getElementsByTagName('input');
var input_cont_two_name_array = [];
for(j=0;j<input_two.length;j++){
input_cont_two_name_array.push(input_two[j].name);
}
for(i=0;i<inputs.length;i++){
input_name_id = inputs[i].name;
if(input_cont_two_name_array.indexOf(input_name_id) == -1){
//do your stuff
}
}

Meteor - Data saving issue

I have this template:
<Template name="nuevoEjercicio">
<div class="container-fluid">
<div class="form-group">
<input type="text" class="form-control input-lg" name="ejercicio" placeholder="Ejercicio?"/>
<input type="number" class="form-control" name="repeticiones" placeholder="Repeticiones?" />
<input type="number" class="form-control" name="peso" placeholder="Peso?" />
<button type="submit" class="btn btn-success" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</Template>
that I use to capture and save to the database.
Then on my .js file I am trying to get the data and save it:
Template.nuevoEjercicio.events({
'click .btn btn-success': function (event) {
var ejercicio = event.target.ejercicio.value;
var repeticiones = event.target.repeticiones.value;
var peso = event.target.peso.value;
ListaRutina.insert({
rutina:"1",
ejercicio:ejercicio,
repeticiones:repeticiones,
peso:peso,
});
// Clear form
event.target.ejercicio.value = "";
event.target.repeticiones.value = "";
event.target.peso.value = "";
// Prevent default form submit
return false;
}
});
}
as I understand, when I click on any object that has the btn btn-success style....but is not the case. For some obscure reason -for me- is not working.
Can you check it and give me some advice?
Thanks!
First of all, there's an error in you selector. It's 'click .btn.btn-success', not 'click .btn btn-success'.
Also you can't do that event.target.ejercicio.value thing. event.target is the element that was clicked. You'll have to do something like this:
'click .btn.btn-success': function (event, template) {
var ejercicio = template.$('[name=ejercicio]').val()
...
OK
What after wasting hours and hours the solution is:
1- on the html file give your input an id:
<input type="number" class="form-control" **id="peso"** placeholder="Peso?" />
<button type="submit" class="btn .btn-success" id="**guardar**" />
so now you want to save data on the input when the button is clicked:
2- You link the button with the funcion via the id
Template.TEMPLATENAMEONHTMLFILE.events({
'click **#guardar**': function (event, template) {
var ejercicio = template.$("**#peso**").val();
and get the value linking using the input id.

clear form values with reset button

Alright I could use a small tip here:
I have a form with two buttons, one has to submit the form and the other one has to reset the complete form.
The text - field keeps its value after every submit, but I would like to clear it completely with the reset button
<form method="post">
<input type="text" name="text" value="Clear Me Please">
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
</form>
I have a input field, submit button and a reset button. Upon submiting the form the user input will be inserted as value, because I dont want to lose the input. Now, when I type something into the field I can reset the form as planed, but after submiting the value now stays as supposed, but pressing the reset button resets the input to the value.
Example: I type in "TEXT", press Reset, gets reseted to "". Type "TEXT2", press Submit, gets submited, put in as value, field has now "TEXT2" written in. Replace "TEXT2" with "TEXT3", press Reset, now field contains "TEXT2" instead of "". I hope this is explaination enough.
may a little bit more you have to do
But his may help-Using Jquery
Edited Version:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
jQuery("#btn").on('click', function(e)
{
document.getElementById("myForm").reset();
$('#input').attr("value", "");
});
});
</script>
</head>
<form id="myForm" method="post">
<input type="text" name="input" id="input" value="<?= $_POST['input'] ?>"><br>
<button type="submit">Submit</button>
<input type="button" id="btn" value="Reset">
</form>
Orginal Version:
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
jQuery(document).ready(function() {
jQuery("#btn").on('click', function(e)
{
values= $('#fname').val();
document.getElementById("myForm").reset();
$('#fname').attr("placeholder", values);
});
});
</script>
<head>
<form id="myForm">
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" id="btn" value="Reset form">
</form>
jsfiddle linkhere

HTML required readonly input in form

I'm making a form. And on one input tag is an OnClick event handler, which is opening a popup, where you can choose some stuff, and then it autofills the input tag.
That input tag is also readonly, so only right data will be entered.
This is the code of the input tag:
<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();" />
But the required attribute isn't working in Chrome. But the field is required.
Does anybody know how I can make it work?
I had same requirement as yours and I figured out an easy way to do this.
If you want a "readonly" field to be "required" also (which is not supported by basic HTML), and you feel too lazy to add custom validation, then just make the field read only using jQuery this way:
IMPROVED
form the suggestions in comments
<input type="text" class="readonly" autocomplete="off" required />
<script>
$(".readonly").on('keydown paste focus mousedown', function(e){
if(e.keyCode != 9) // ignore tab
e.preventDefault();
});
</script>
Credits: #Ed Bayiates, #Anton Shchyrov, #appel, #Edhrendal, #Peter Lenjo
ORIGINAL
<input type="text" class="readonly" required />
<script>
$(".readonly").keydown(function(e){
e.preventDefault();
});
</script>
readonly fields cannot have the required attribute, as it's generally assumed that they will already hold some value.
Remove readonly and use function
<input type="text" name="name" id="id" required onkeypress="return false;" />
It works as you want.
Required and readonly don't work together.
But readonly can be replaced with following construction:
<input type="text"
onkeydown="return false;"
style="caret-color: transparent !important;"
required>
1) onkeydown will stop manipulation with data
2) style="caret-color: transparent !important;" will hide cursor.
3) you can add style="pointer-events: none;" if you don't have any events on your input, but it was not my case, because I used a Month Picker. My Month picker is showing a dialog on click.
This is by design. According to the official HTML5 standard drafts, "if the readonly attribute is specified on an input element, the element is barred from constraint validation." (E.g. its values won't be checked.)
Yes, there is a workaround for this issue. I found it from https://codepen.io/fxm90/pen/zGogwV site.
Solution is as follows.
HTML File
<form>
<input type="text" value="" required data-readonly />
<input type="submit" value="Submit" />
</form>
CSS File
input[data-readonly] {
pointer-events: none;
}
If anyone wants to do it only from html, This works for me.
<input type="text" onkeydown="event.preventDefault()" required />
I think this should help.
<form onSubmit="return checkIfInputHasVal()">
<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();" />
</form>
<script>
function checkIfInputHasVal(){
if($("#formAfterRederict").val==""){
alert("formAfterRederict should have a value");
return false;
}
}
</script>
You can do this for your template:
<input required onfocus="unselect($event)" class="disabled">
And this for your js:
unselect(event){
event.preventDefault();
event.currentTarget.blur();
}
For a user the input will be disabled and required at the same time, providing you have a css-class for disabled input.
Based on answer #KanakSinghal but without blocked all keys and with blocked cut event
$('.readonly').keydown(function(e) {
if (e.keyCode === 8 || e.keyCode === 46) // Backspace & del
e.preventDefault();
}).on('keypress paste cut', function(e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="readonly" value="test" />
P.S. Somebody knows as cut event translate to copy event?
Required and readonly don't work together.
Although you can make two inputs like this:
<input id="One" readonly />
<input id="Two" required style="display: none" /> //invisible
And change the value Two to the value that´s inside the input One.
I have the same problem, and finally I use this solution (with jQuery):
form.find(':input[required][readonly]').filter(function(){ return this.value === '';})
In addition to the form.checkValidity(), I test the length of the above search somehow this way:
let fcnt = $(form)
.find(':input[required][readonly]')
.filter(function() { return this.value === '';})
.length;
if (form.checkValidity() && !fcnt) {
form.submit();
}
function validateForm() {
var x = document.forms["myForm"]["test2"].value;
if (x == "") {
alert("Name missing!!");
return false;
}
}
<form class="form-horizontal" onsubmit="return validateForm()" name="myForm" action="" method="POST">
<input type="text" name="test1">
<input type="text" disabled name="test2">
<button type="submit">Submit</button>
</form>

Submit Search on Enter Key?

What needs to be done to have this form submitted when someone hits the 'enter' key?
<form id="search" onsubmit="javascript:search(document.getElementById('searchText'))">
<input type='text' id='searchText' autofocus />
<input type='button' onclick="search(document.getElementById('searchText'))" value='Search' />
</form>
You can just use a form as below, with input type submit, which in this case, if you press enter in any input - if you had more of them - it will be a default behaviour of the form to be submitted:
<form id="search">
<input type='text' id='searchText' />
<input type='submit' value='Search' />
</form>
or, as it shows, you want to use the onsubmit function and handle the "submit" of the form, so you can do this:
<form id="search" action="#">
<input type="text" id='searchText' name="myinput" onkeypress="handle" />
</form>
<script>
function handle(e){
if(e.key === "Enter"){
alert("Enter was just pressed.");
}
return false;
}
</script>
A code, quite the same, can be found on this similar question: How to capture Enter key press?
Hope I answered your question, even out of time.
This example worked perfectly for me:
var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
I took the example at w3schools.