javascript add two multipleevents on input field - javascript

I am trying to add two events on input field like onkeyup and onchange, the purpose is to avoid longpress of characters other than numbers..as the field is for zipcode. At present only one event is working either keypress/onchange.
I am adding my code for refrence any help would be appreciated.
function zipchange(obj, selector){
var code = obj.value;
var isnum = /^\d+$/.test(code);
if(!isnum)
obj.value="";
}//onchange
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
obj.value = code.substring(0,4)+'-'+substr;
}//onkeypress
//html
<input id="pincode" type="text" data-validate="validate[required]" name="address.pinCode" required="true" onkeyup="autoZip(this)" onchange="zipchange(this)" msg="Enter valid zip code" />
Answer:
function autoZip(obj, selector){
var code = obj.value;
if(code.match(/\D/gi))
obj.value = code.replace(/\D/gi,'');
if(code.length>4 && code.indexOf('-')== -1){
var substr = code.substring(4);
substr=substr.replace(/\D/gi,'');
var substr1 = code.substring(0,4);
obj.value = substr1+'-'+substr;
var isnum = /^\d+$/.test(substr1)
if(!isnum)
obj.value="";
}
Hi the above modified function did the trick..thanks for all the enlightned ones who helped me..

Well first of all onchange is triggered when you change the content of the text-box and when you loose focus from input type
Hence there is no use in using onchange event you have to implement your onchange logic in keyup event

Related

Verify input value

I'm trying to read a value from an input an verify if it's a certain number of my choosing. What I've got so far is:
const input = document.getElementById('input');
var val = parseInt(input.value);
input.addEventListener('input', () => {
if(val == 1){
alert('test')
}
})
<input id="input">
But it doesn't work as intented. There is barely any code here so the solution must be simple but I can't find it, any help would be appreciated.
Put,
const input = document.getElementById('input');
var val = parseInt(input.value);
inside the listener like below
input.addEventListener('input', () => {
const input = document.getElementById('input');
var val = parseInt(input.value);
if(val == 1){
alert('test')
}
})
<input id="input">
Try using a type attribute in your input.
<input type="number" id="input" />
And in your JavaScript, use input.innerHTML instead of input.value, that way it returns the most updated value.
And 'input' is not a JavaScript Event.
input.addEventListener('oninput', function () {});
//Or, The Way I Would Prefer:
input.addEventListener('onchange', function () {});

HTML button not functioning

I am working on a project in JavaScript, which prints out some names pulled from an XML file. I also have 3 textboxes and an update button so that if anyone types in a name in any of the textboxes, they will see the updated names when they hit the button. For example, if I originally have:
George
Mary
John
If the user types in Jane, it should change the output to:
Jane
Mary
John
However, the update button doesn't do anything when it is clicked on. Here is the code for my 3 textboxes and the button:
<div id = "Names">
<input type = "text" id = "nameOne" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "text" id="nameTwo" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type ="text" id = "nameThree" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "button" id = "btnUpdate" value = "Update Names" onClick = "printNames()" /></div>
And here are the functions I am using:
function getXML(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Names.xml",false);
xmlhttp.send();
return(xmlhttp.responseXML);
}
function printNames() {
var xml = getXML();
var txt = "";
$(xml).find("person").each(function () {
txt += "<div>" + $(this).text() + "</div>";
});
$("body").append(txt);
insertNames(name1, name2, name3);
}
function insertNames(name1, name2, name3) {
var xmlRequest = getXML();
var nameOneTxt = document.getElementById('nameOne').value;
var nameTwoTxt = document.getElementById('nameTwo').value;
var nameThreeTxt = document.getElementById('nameThree').value;
if (nameOneTxt != null || nameTwoTxt != null || nameThreeTxt != null) {
var x = xmlRequest.getElementsByTagName("person")[0].childNodes[0];
x.nodeValue = nameOneTxt;
var y = xmlRequest.getElementsByTagName("person")[0].childNodes[1];
y.nodeValue = nameTwoTxt;
var z = xmlRequest.getElementsByTagName("person")[0].childNodes[2];
z.nodeValue = nameThreeTxt;
}
printNames();
}
printNames();
</script>
The printNames() function reads the names from an XML file and outputs those names using jQuery. It then calls the insertNames() function which takes in 3 parameters (for the three textboxes I have.)
The insertNames function opens an XML connection, and then gets the values for each textbox. If the textbox is not null, then that means the user input a value, in which case, a call to the XML tag is made and updates the existing content to the user input. It then calls the printNames() function which outputs the new contents.
When I test this, I get the original names output, but the update button doesn't do anything. I tried adding a print statement to the insertNames function to find that the function never runs. What am I missing? Any help would be appreciated. Thanks.
I think it is when the function is being loaded. Check this
Fiddle.
I have reduced your printNames call to this
function printNames(){
alert(1);
}
If you leave it to run at default onLoad it doesn't work. If you change the load time to No wrap -in Body it works fine.
Haven't seen your code, but check where you are loading the function in relation to the onclick. The manual printNames() call at the bottom of the script will work whereas the onclick printNames() call will not.

entry in input one by one should show added result in result field

when user select any option in radio buttons in group one and then enter any number in respective input field and then select the next any radio option and enter any value in input field then this time it should add the new result with old one and display it in result input field and now if he empty any input field then that should also minus from the total result and display it in result field.
i have so many groups like that but here i just put two of them to get the result.
here id the FIDDLE
here is the jquery code. i can work in jquery but not very good i used separate code for every group and i know there must be a way to get this whole functionality through generic code but again i am not good at jquery
jQuery("#txt_im").keyup(setValue);
jQuery('[name="rdbtn-im"]').change(setValue);
function setValue() {
var txt_value = jQuery("#txt_im").val();
var rad_val = jQuery('[name="rdbtn-im"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res = txt_value * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
var final2 = 0;
jQuery("#txt_fb").keyup(setValue2);
jQuery('[name="rdbtn-fb"]').change(setValue2);
function setValue2() {
var txt_value = jQuery("#txt_fb").val();
var rad_val = jQuery('[name="rdbtn-fb"]:checked').val();
if(!txt_value.length) {
jQuery('#final_res').val('');
return;
}
if (!rad_val.length) return;
var res2 = txt_value * rad_val;
final2 = parseInt(res2, 10) + final;
var MBresult = final2 / 1024;
jQuery('#final_res').val(MBresult.toFixed(2));
}
infact user is free to select any number of groups or also free to remove any number of group after selection.
i know there is error in fiddle when user select 2nd group after the select of first it removes the result which is wron and i tried to solve it but failed but i define the whole seen what i need to do. i will be very thankfull to you for this kind favour.
HTML:
<table>
<tr>
<td>
<input type="radio" name="rdbtn-im" id="rdbtn-im-day" value="25" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-im" id="rdbtn-im-week" value="175" class="rdbtn-style-social" />Weekly
<input type="text" name="txb3" id="txt_im" class="txt-email" style="width:100px;margin: 2px;" />
</td>
</tr>
<tr>
<td class="sec-td-rdbtns-social">
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-day" value="3500" class="rdbtn-style-social" />Daily
<input type="radio" name="rdbtn-fb" id="rdbtn-fb-week" value="500" class="rdbtn-style-social" />Weekly
<input type="text" name="txb1" id="txt_fb" class="txt-email" style="width:100px;margin: 2px;" /> </td>
</tr>
</table>
<br>result
<input type="text" name="final_res" id="final_res" class="" style="width:100px;margin: 2px;" />
Jquery:
jQuery(".txt-email").keyup(setValue);
jQuery('.rdbtn-style-social').change(setValue);
function setValue() {
var total = 0;
$(".rdbtn-style-social:checked").each(function () {
var myInput = $(this).siblings(".txt-email").val();
if (myInput.length) {
total += myInput * $(this).val();
}
});
if (total) {
jQuery('#final_res').val((total / 1024).toFixed(2));
} else {
jQuery('#final_res').val('');
}
}
FIDDLE
If you are using chrome, then console is your best friend ( https://developers.google.com/chrome-developer-tools/docs/console )
For firefox you have firebug, opera has dragonfly (or something like that ?). Even IE has console now. There you can see all errors popping up.
Ok, so first of all let's clean up this a little bit by wrapping it all in closure (we can now safely use the $ instead of jQuery even if there is namespace conflict outside). Also, we will use single function for both cases, because they are so similar.
!function ($) {
$(".txt-email").keyup(setValue);
$('.rdbtn-style-social').change(function(e) { setValue(e, true) });
function setValue(e, radio) {
if('undefined' === typeof radio) radio = false;
var attr = radio ? 'name' : 'id';
var tmp = e.target[attr].split('-');
var media = tmp[tmp.length - 1];
var txt_value = $("#txt-"+media).val();
var rad_val = $('.rdbtn-style-social[name="rdbtn-'+media+'"]:checked').val();
if (!txt_value.length || !rad_val.length) {
$('#final_res').val('');
return false;
}
var res = (txt_value | 0) * rad_val;
var final = parseInt(res, 10);
var MBresult = final / 1024;
$('#final_res').val(MBresult.toFixed(2));
}
}(jQuery);
(variable | 0 is same as parseInt(variable, 10)).
So, long story short: when radio or text gets changed, the function is fired (if it's radio, additional argument is passed). We retrieve whether we want to work on im or fb, then do whatever you want. I changed id of inputs to replace _ with -'s (for split consistency)
Final jsfiddle: http://jsfiddle.net/Misiur/f6cxA/1/

the best practice for assigning an ID automatically

I have a page that contains a link like this:
new user
When the user clicks the link, I add a new input field to the page. I would like to assign an ID to that input field. I can do this using Javascript:
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.setAttribute('ID',"input"+num);
}
This works; but my question is, is this the standard way, or is there a better way to do this, something that doesn't use num, JS or jQuery?
You don't need an ID on an input element. However you might be needing a name. If so, just use name = "input[]" - then on the server side you will get an array of values.
Since you're using jQuery:
$('<input id="input'+ num +'"/>').appendTo('#yourElement')
Just assign the id to the element:
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.id = "input" + num;
}
Since you tagged your question with jQuery, you can also do this:
function add(){
var input = $('<input id="input' + num++ +'" />')
// do something with the input.
}
Or:
function add(){
var input = $('<input>', {id = "input" + num++});
// do something with the input.
}
Update:
You can't create DOM elements without javascript (jQuery is javascript).
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.id = "input"+num;
}
random ID without num :
function add(){
var input = document.createElement('input');
input.id = 'input'+parseInt(Math.random()*1354243242);
}

Javascript form validation

I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}

Categories