HTML Script capturing text and performing events with its own value - javascript

I'm trying to capture the value of 2 text inputs and performs functions when the user press enter key.
I'm using Internet Explorer 11.
<script type="text/javascript">
function myFuncion(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
</script>
Now, the text inputs code
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion('" + document.getElementById("idText").textContent + "', '"
+ document.getElementById('idAnotherText').value + "');
}"
/>
<input type="text" size="6" name="nameText" id="idText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion('" + document.getElementById("idText").textContent + "', '"
+ document.getElementById('idAnotherText').value + "');
}"
/>
Is it not working.
Unfortunately this not works:
<button onclick="myFuncion('" +
document.getElementById(\"idAnotherText\").textContent + "', '" +
document.getElementById(\"idText\").textContent + "')" >Press Me</button>
<button onclick="myFuncion(" +
document.getElementById(\"idAnotherText\").textContent + ", " +
document.getElementById(\"idText\").textContent + ")" >Press Me</button>
<button onclick="myFuncion(" +
document.getElementById('idAnotherText').textContent + ", " +
document.getElementById('idText').textContent + ")" >Press Me</button>
How solve this?
Or something https://stackoverflow.com/a/155272/811293 but is not working:

Remove quotes from the function arguments. You also have to use value instead of textContent to grab the values from input fields in both cases. Try the following:
function myFuncion(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion(document.getElementById('idText').value, document.getElementById('idAnotherText').value);
}"
/>
<input type="text" size="6" name="nameText" id="idText" value=""
onkeydown = "if (event.keyCode == 13) {
myFuncion(document.getElementById('idText').value, document.getElementById('idAnotherText').value);
}"
/>
Writing JavaScript in HTML is not a good idea. You might do the following which is more cleaner:
function myFuncion(event) {
if (event.keyCode == 13) {
var txt1 = document.getElementById('idText').value;
var txt2 = document.getElementById('idAnotherText').value;
window.alert("txt1:" + txt1 + ", txt2:" + txt2);
}
}
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value="" onkeydown = "myFuncion(event);"/>
<input type="text" size="6" name="nameText" id="idText" value="" onkeydown = "myFuncion(event);"/>

If you are in a form with a submit button you need to return false from your event handler or your form will auto submit when return is pressed while in an input.
As a general rule you should avoid trying to handle Return presses in inputs in a form. This breaks the expected behavior of forms on the internet which is that they submit when return is pressed. Instead register a callback on the submit event of the form and do it (validations, ajax, etc.) there instead.

Rewriting the javascript makes it work. In general avoid putting actual code into the code
With this as the javascript
function myOnKeyDown(event) {
if (event.keyCode == 13) {
var text_value = document.getElementById("idText").value
var another_text_value = document.getElementById("idAnotherText").value
myFunction(text_value, another_text_value);
}
}
function myFunction(arg1, arg2) {
window.alert("arg1:" + arg1 + ", arg2:" + arg2);
}
You can have this in your html
<input type="text" size="6" name="nameAnotherText" id="idAnotherText" value="" onkeydown="myOnKeyDown(event)"/>
<input type="text" size="6" name="nameText" id="idText" value="" onkeydown="myOnKeyDown(event)"/>
This should allow your code to run.

I usually try to go as native as possible.
The way you can go about is to wrap the input fields with form tag and add event listener to the submit event.
Try the following.
const form = document.getElementById('myform');
form.addEventListener('submit', onSubmit, false);
form.submit = onSubmit;
function onSubmit(event) {
if (event) {
event.preventDefault();
}
console.log('submitted');
const input1 = document.getElementById('input1').value;
const input2 = document.getElementById('input2').value;
console.log({
input1,
input2
});
}
<form id="myform">
<input type="text" id="input1">
<input type="text" id="input2">
<button type="submit" style="display: none"></button>
</form>

Related

Preventing global jQuery event on single form item

When my JS code loads I call the following which adds a onkeypress event to all text inputs:
$('#myForm input[type=text]').keypress(function(event) {
sysOnEnter(event, $('#myForm input[type=text]').attr('id'), modalId);
});
The function sysOnEnter is to click a button when the user presses the Enter/Return key:
function sysOnEnter(event, id, modalId) {
var key = event.key || event.keyCode;
if (key == 'Enter' || key == 13) {
var val = $('#' + id).val();
setTimeout(function() {
if ($('#' + id).val() == val)
document.querySelector('#' + modalId + ' .btn-primary').click();
},0);
event.preventDefault();
return false;
}
}
The time that I don't want this to happen is when using Google's auto-suggest address form:
<input
id = "autocomplete"
class = "form-control"
placeholder = "Start typing..."
onFocus = "initAutocomplete();geolocate();"
type = "text"
>
Is there an easy way to exclude this particular field from the javascript function?
Use the selector :not(#autocomplete) to exclude the element with the autocomplete id:
$('#myForm input[type=text]:not(#autocomplete)').keypress(function(event) {
console.log('firing event');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text">
<input type="text">
<input type="text" id="autocomplete" placeholder="autocomplete">
<input type="text">
</form>
If the field you want to exclude is known beforehand you can use JQuery .not():
$('#myForm input[type=text]').not("#autocomplete").keypress(function(event) {

Javascript/jQuery : Detect both return key press and submit button press simultaneously

I have an input field and an "add" button below it. What the add button basically does is, it appends a new input field to the document. What I am trying to do here is, while typing in an input field if return key press is detected the function that calls the addition of new input field is fired the same function that is fired when the add button is clicked.
Can I incorporate the detection of return key press in the following somehow?
$('.addNewSite').on('click', function(){
var idNewInput = "site" + numInputFields;
$('.inputFieldsSettingsPanel').append('<input type="text" class="tracksiteInput" id = "' + idNewInput + '"></input>');
$("#" + idNewInput).focus();
});
I think you want this http://jsfiddle.net/naeemshaikh27/cy84t4pz/
function fun(){
$('body').append('<input type="text"/>');
}
$('.addButton').on('click', fun);
$('body').on('keypress','input', function(e){
if (e.keyCode == 13) {
fun();
}
});
something like this? e.which in the keypress() is what you're looking for to see what button is pressed. in this case, 13 is equivalent to the enter key
$(document).ready(function() {
$('.add').on('click', function() {
var html = '<input type="text" class="field" /><br/><br/>';
$('.form').append(html);
});
$(document).on("keypress", ".field", function(e) {
if(e.which == 13) {
$('.add').trigger('click');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a class="add" href="#">add</a><br/><br/>
<div class="form">
<input type="text" class="field" /><br/><br/>
<input type="text" class="field" /><br/><br/>
</div>
You cant detect enter keypress on the input and trigger the button's click event.
$("button").on("click", function(e){
$("body").append($("<input>").attr("type", "text"));
});
$(document).on("keypress", "input", function(e){
if(e.which == 13) $("button").trigger("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add Input</button>
var i;
var inputs=document.getElementsByClassName('add');
for(i=0;i<inputs.length;i++){
inputs[i].addEventListener('keyup',function(event){
if(event.keyCode){if (event.keyCode=="13" ){createNewElem();
}}
//if(event.which){if(event.which =="13"){alert('return pressed');}}
});
}
function createNewElem(){
var newinput=document.createElement('input');
var inptype=document.createAttribute('type');
inptype.value="text";
newinput.setAttributeNode(inptype);
var inpclass=document.createAttribute('class');
inpclass.value="add";
newinput.setAttributeNode(inpclass);
document.body.appendChild(newinput);
}
<input type="text" class="add" />

fill input if radio is selected using jquery

I have a input and two radio buttons.
The input accepts a number for a time period a person lives at a residence.
The radio buttons are months & years.
I want to fill a 2nd input using the 1st input value (numerical value of length at residence) and either the value for months or years based on the radio selected.
I've made it spit out the time, but it spits out the value for both radio button because I did not have an if statement to check. I already have jquery in my form and it works. I just need this small section of my form to work.
My question is, how do I set up the conditional statement for checking what radio is checked?
HTML
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months
jQuery
$('#months').click(function () {
if ($(this).attr("checked") == "checked") {
$('#homeLength, #months').bind('keypress blur', function () {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#months').val() + ' ' + ' ');
});
}
});
$('#years').click(function () {
if ($(this).attr("checked") == "checked") {
$('#homeLength, #years').bind('keypress blur', function () {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val() + ' ');
});
}
});
You need to check the checked radio's value only and do that on keyup/blur AND click of any radio
$(function() {
$('#homeLength').on('keyup, blur', function() {
var lgt = $("input:radio[name=length]:checked").val();
$('#homeTime').val($(this).val() + ' '+lgt);
});
$("input:radio[name=length]").on("click",function() {
$('#homeLength').blur(); // trigger the blur event of the field to update
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" value="" required maxlength="5" class="form-control" name="homeLength" id="homeLength">
<input type="radio" id="years" value="Years" name="length" required> Years
<input type="radio" id="months" value="Months" name="length"> Months
<hr/>
<input type="text" value="" class="form-control" name="homeTime" id="homeTime">
The most usable conditional statement for this kind of checkings is:
if ($(this).is(':checked'))
so as you can see the response is boolean.
Replave your javascript code with this
$('#months').click(function() {
console.log($(this).prop('id'));
$('#homeLength, #months').bind('keypress blur', function() {
$('#homeTime').val($('#homeLength').val() + ' ' + ' '+$('#months').val()+ ' ' + ' ');
});
});
$('#years').click(function() {
console.log($(this).prop('id'));
$('#homeLength, #years').bind('keypress blur', function() {
$('#homeTime').val($('#homeLength').val() + ' ' + ' ' + $('#years').val()+ ' ');
});
});
whenever user will select any radio button u can get its id by
$(this).prop('id');
its value by
$(this).prop('value');

Unable To Send Emails With JavaScript

An old thread on Stack Overflow discusses how to use JavaScript to fill in a mailto email:
Sending emails with Javascript
I was interested in applying the technique, but couldn't get it to work.
In the code below, when I set a breakpoint on return false in the makecontact() method, and look at the URL that it logs, it looks fine.
But the browser does not open the email client.
If I hardcode the same URL in an href in the Submit button, then it launches the email client.
Why doesn't setting the href work?
ANSWER: It was the wrong href.
Fixed version:
<!-- TODO: Validate name and text fields and don't allow submit until they are valid. Limit total mailto URL length to 2000. -->
<form name="contact">
<br/>Reason for contact:
<br/>
<input type="radio" name="reason" value="Product Inquiry/Presales Questions" checked="checked"/>Product Inquiry/Presales Question<br/>
<input type="radio" name="reason" value="Support/Warranty"/>Support/Warranty<br/>
<input type="radio" name="reason" value="Feedback"/>Feedback<br/>
<input type="radio" name="reason" value="Other"/>Other<br/>
<input type="text" name="name" id="name"/>Your name:</div>
<textarea name="contacttext" rows="20" cols="60" id="contacttext"></textarea>
<button id="submit">Submit</button>
</form>
<script type="text/javascript" id="contactjs">
<!--
var submit = document.getElementById("submit");
function getreason() {
var radios, i, radio;
radios = document.getElementsByName("reason");
for (i = 0; i < radios.length; i += 1) {
radio = radios[i];
if (radio.checked) {
break;
}
}
return encodeURIComponent(radio.value);
}
function makecontact(e) {
var subject, name, text;
subject = getreason();
name = document.getElementById("name").value;
text = document.getElementById("contacttext").value;
body = "From: '" + name + "', Content: '" + text + "'";
body = encodeURIComponent(body);
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
console.log(document.location.href);
e.preventDefault();
return false;
}
if (submit.addEventListener) {
submit.addEventListener("click", makecontact, true);
} else if (form.attachEvent) {
submit.attachEvent("onclick", makecontact);
} else {
submit.click = makecontact;
}
//-->
</script>
</div>
body = "From: '
" + name + "
', Content: '
" + text + "
'";
This is not valid JavaScript. It will cause an "Unterminated string constant" error. Try this instead:
body = "From: '\n" + name + "\n', Content: '\n" + text + "\n'";
You have two main problems:
button elements don’t have hrefs (HTML4, HTML5). Setting one won’t do anything. At the end of your submit handler, you should instead set document.location.href:
document.location.href = "mailto:contact#analogperfection.com?Subject=" + subject + "&Body=" + body;
You can’t have literal newlines in strings in JavaScript. Use \n instead:
body = "From: ' \n" + name + " \n', Content: ' \n" + text + " \n'";
Also be aware…
You should accept an event object in your event handler, and call event.preventDefault() instead of just returning false from your event handler, to stop the form from being submitted.
There’s no function called resume, but you’re using it if neither addEventListener nor attachEvent exists.

jquery get all input from specific form

Is there any ways to populate all of the input from certain form?
let say, some thing like this:
<form id="unique00">
<input type="text" name="whatever" id="whatever" value="whatever" />
<div>
<input type="checkbox" name="whatever" id="whatever" value="whatever" />
</div>
<table><tr><td>
<input type="hidden" name="whatever" id="whatever" value="whatever" />
<input type="submit" value="qweqsac" />
</td></tr></table>
</form>
<form id="unique01">
<div>
<input type="text" name="whatever" id="whatever" value="whatever" />
<input type="checkbox" name="whatever" id="whatever" value="whatever" />
</div>
<table><tr><td>
<input type="hidden" name="whatever" id="whatever" value="whatever" />
</td></tr></table>
<select>blah...</select>
<input type="submit" value="qweqsac" />
</form>
etc forms... forms...
*note: each form might have a different amount of input and type and also different html structure
so is there any way to populate the input from certain form id? eg if i click submit button from certain form id, then jquery will populate for me all of the input within those form id.
currently what i'm doing is like this:
$("form").submit(function(){ return validateForm($(this)) });
function validateForm(form){
var retVal = true;
var re;
$.each(form.serializeArray(), function(i, field) {
var input = $('input[name='+field.name+']');
field.value = $.trim(field.value);
switch(field.name){
case "name" :
and another cases...
}
})
}
that was work,
but in that case, i only get the field.name and field.value, and actually what i want is, i want a jquery object for each input element, so i can access their css, id, name, and even animate those input element
is there any way for this?
please let me know and thank you in advance!
AnD
To iterate through all the inputs in a form you can do this:
$("form#formID :input").each(function(){
var input = $(this); // This is the jquery object of the input, do what you will
});
This uses the jquery :input selector to get ALL types of inputs, if you just want text you can do :
$("form#formID input[type=text]")//...
etc.
The below code helps to get the details of elements from the specific form with the form id,
$('#formId input, #formId select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements from all the forms which are place in the loading page,
$('form input, form select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
The below code helps to get the details of elements which are place in the loading page even when the element is not place inside the tag,
$('input, select').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
NOTE: We add the more element tag name what we need in the object list like as below,
Example: to get name of attribute "textarea",
$('input, select, textarea').each(
function(index){
var input = $(this);
alert('Type: ' + input.attr('type') + 'Name: ' + input.attr('name') + 'Value: ' + input.val());
}
);
Use HTML Form "elements" attribute:
$.each($("form").elements, function(){
console.log($(this));
});
Now it's not necessary to provide such names as "input, textarea, select ..." etc.
$(document).on("submit","form",function(e){
//e.preventDefault();
$form = $(this);
$i = 0;
$("form input[required],form select[required]").each(function(){
if ($(this).val().trim() == ''){
$(this).css('border-color', 'red');
$i++;
}else{
$(this).css('border-color', '');
}
})
if($i != 0) e.preventDefault();
});
$(document).on("change","input[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
$(document).on("change","select[required]",function(e){
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});

Categories

Resources