replacing commas with slashes in JavaScript - javascript

I am trying to replace , with / in JavaScript and wrote the code below. There are multiple text boxes available in the form. I want to write a single function and call them on all the text fields.
The issue that I am experiencing is that I am not able to send the current ID to the JavaScript method. How is this properly done?
function removeComma(val) {
var values = document.getElementById('val').value; //Object Required Error
var n=values.replace(/,/, "/");
document.getElementById('val').value=n;
}
<input type="text" id="one" name="one" onkeypress="removeComma(this)">
<input type="text" id="two" name="two" onkeypress="removeComma(this)">
<input type="text" id="three" name="three" onkeypress="removeComma(this)">
The error that I am getting from above code is OBJECT REQUIRED at first line.

You're passing the clicked element to your function, hence you don't need document.getElementById() at all. This fixes your problem.
function removeComma(val) {
var values = val.value;
var n=values.replace(/,/g, "/");
val.value=n;
}
Notice also, that onkeypress is fired before the value of the input element is changed. You can use onkeyup or rather oninput if you want to use the last updated value of input.
If you really have to use the id of the element, you need to pass it in the argument:
<input type="text" id="one" name="one" onkeypress="removeComma(this.id)">
And then also remove the quotes around val:
var values = document.getElementById(val).value;

document.getElementById('val')
should be
document.getElementById('one')
If you make this change you don't need to send this to removeComma.
If you keep this then use the following function
function removeComma(val) {
var values = val.value;
var n=values.replace(/,/, "/");
val.value=n;
}

It should be...
document.getElementById(val).value
... instead, as you're probably going to call this function for each input textbox separately, sending their ids as params into the function.
UPDATE: ... and your edit clearly shows even that's not the case: you're passing an element itself into a function. That's good, but then you don't have to look after that element with document.getElementById - you already have it.
Still, there're another issue here: if you need to replace all commas, you need to add /g modifier to that regex. Otherwise multiple commas (added by copy-pasting, for example) won't be replaced.
Overall, I'd rewrite it like this:
function removeComma(el) {
el.value = el.value.replace(/,/g, '/');
}
Here's a fiddle to play with (and here's its fork working with oninput handlers instead - in my opinion, the latter is smoother).

Related

Javascript - Use document.getelementbyid().value with a variable

I'm trying to capture the value of a text field on an HTML form using document.getElementById(my_field).value where the variable my_field is passed to my function dynamically, but am hitting a wall.
How do you use a variable in this context?
The function just doesn't seem to parse the contents of the variable my_field, instead treating it as a string no matter whether I use quotes, square brackets or curly braces.
function myFunction() {
var my_field = arguments[0];
var current_value = document.getElementById(my_field).value;
alert ("Current Value: " + current_value);
}
I'm doing it this way because I have multiple records on a form and each row has its own unique id for the required field.
Running the above just does nothing. The alert never pops which I assume is because current_value never gets set.
To add further detail - I tried to simplify everything for the purposes of this question as there's lots of other unnecessary complications that will only detract from the main issue - on my HTML form is a text field which calls my function on onChange
onchange="enforce_multiples('quantity[<?php echo $line_id; ?>]',<?php echo $product['minimum'];?>)"
I've checked that arguments[0] and [1] are being captured correctly by outputting their values to an alert. Everything works fine up until I try to set the quantity_entered value.
<script>
function enforce_multiples() {
var line_id = arguments[0];
var quantity_increments = arguments[1];
var quantity_entered = document.getElementById([line_id]).value;
alert("QE" + quantity_entered);
//var quantity_mod = quantity_entered % quantity_increments;
//var revised_quantity = quantity_entered - quantity_mod;
//alert("RQ: " + revised_quantity);
//document.getElementById([line_id]).value = revised_quantity;
}
</script>
Checked the console and I receive the error: Uncaught TypeError: Cannot read property 'value' of null on the geElementById line
You should write document.getElementById(my_field) instead of document.getelementbyid(my_field).
OK so I got to the bottom of this in case anyone is interested.
In order to use a variable in document.getElementById() you simply add the variable name with no quotes.
var my_variable = "field1";
document.getElementById(my_variable);
The reason this wasn't working on my form was because the text fields only had the name parameter and not an id parameter.
So I needed to change:
<input type="text" name="field_name" value="1234" />
To
<input type="text" name="field_name" id="field_name" value="1234" />
And that sorted it. Otherwise I was just getting generic NULL error messages in the console.

How to pass input field name as an argument in javascript function?

I've created a JavaScript function that checks if a certain data already exists in my database. What I want to know is if there is a way to make the input field name in a JavaScript pass as an argument
Here is my code
function checkDataAvailability(displayid,input_id,fieldname)
{
'use strict';
$(document).ready(function(){
//var x = document.getElementByName(fieldname).elements;
$(displayid).load('php/signcheck.php').show();
$(input_id).keyup(function(){
},
$.post('php/signcheck.php', { username: form.x.value },
//$.post('php/signcheck.php', { username: form.fieldName.value },
function(result){
$(displayid).html(result).show();
});
});
});
}
var a = checkDataAvailability ('#userstat','#username_input','username');
A little explanation. The two commented lines are the two methods I've tried to run the field name as an argument separately. Unfortunately they aren't working.
Here is my form
<form action="php/register_exec.php" method="POST" name="form">
Username <span id="userstat" class="checkerr"></span>
<input type="text" name="username" id="username_input" required>
</form>
Passing form fieldnames as argument is no different than passing string argument to functions
var a = checkDataAvailability ('userstat','username_input','username');
Important thing is what you do inside the function.
You can get the value of input field in primarily two ways
Directly read the value using value property as:
document.getElementById('username_input').value
or
document.getElementById(fieldid).value //if you pass fieldid to your function
Use the form field directly
//assuming you pass formname and fieldname as variables to your function
var form = document.getElementById(formname);
var inputvalue = form.elements.namedItems(fieldname).value
You can modify them to suit your jquery syntax if need be.
Since you're already using the jQuery library, you can continue using it.
$('input[name="' + fieldname + '"]').val()
There are 3 ways of achieving what you desire -
If you want to stick with your current code pattern, then replacing form.fieldname with form[fieldname] would get you the correct results. This is because fieldname is a string, and form."some string" would give you an error.
The other two ways are the same as neouser99 and avck specified in their answers.

How to select and set multiple textboxes text in jquery

Please I have my Jquery code that I want to do few things since. I have a form with a bunch of textboxes. I want to validate each textbox to allow numbers only. To also display error where not number.
var validateForm = function(frm){
var isValid = true;
resetError();
$(":text").each(function(variable){
console.log("The variable is" , variable);
if(!isNormalInteger(variable.val))
{
$("#error"+variable.id).text("Please enter an integer value");
isValid = false;
}
});
if(!isValid)
return false;
};
The above fails. When I print the variable on my console I was getting numbers 0 - 9. My textboxes where empty yet, it returns numbers. I tried variable.val() still fails and return numbers. I modified my select to
$("input[type=text]", frm).each();
Where my form is my form selected by id. It also failed. Below is the example of my html label and textbox. I have about ten of them
<div class="grid-grid-8">
<input class=" text" id="id" name="name" type="text">
<br>
<p class="hint">Once this limit is reached, you may no longer deposit.</p>
<p class="errorfield" id="errorMAXCASHBAL"></p>
Please how do I select them properly? Moreover, my reset function above also returns incrementing integers for value. The p property is of class errorField and I want to set the text property. Please how do I achieve this? Previously I tried the class name only $(.errorField). It also failed. Any help would be appreciated.
var resetError = function(){
//reset error to empty
$("p errorfield").each(function(value){
console.log("the val", value);
//value.text() = '';
});
};
//filter non integer/numbers
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
The main problem is your selectors in javascript. And as laszlokiss88 stated wrong usage of .each() function.
Here is a working example of your code: jsFiddle in this example all .each() functions use $(this) selector inside instead of index and value
You are using .each wrong because the first parameter is the index and the second is the element. Check the documentation.
Moreover, the correct selector for the resetError is: p.errorfield
So, you should modify your code to look something like this:
var resetError = function(){
$("p.errorfield").each(function (idx, element) {
$(element).text("");
});
};
With this, I believe you can fix the upper function as well. ;)

Retrive value from array id in js function

Hi i am writing a php based code in which i am generating checkbox with different id and name
<input type="checkbox" name="settle_check[]" id="settle_check['.$res2['id'].']" value="1" onclick="calculate_discount(\''.$res2['id'].'\');"/>
and my function of calculate discount is as follow
function calculate_discount(id){
alert($('#settle_check['+id+']').val());
if($('#settle_check['+id+']').is(":checked")){
alert('Hiii');
}
else{
alert('Byeee');
}
}
now for every time it is not capturing the value and giving alert of undefined.
Please Help me.
You are using [] in ID selector which are meta characters. You need to escape them.
Use
$('#settle_check\\['+id+'\\]').val()
Docs
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?#[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\.
OR
You can use Attribute Equals Selector [name="value"]
$('[id="settle_check[' + id +']"]').val()
Use this
$('#settle_check\\['+id+'\\]').val()
You can also try this:
Instead of passing the id, pass the element itselfe like:
<input type="checkbox" name="settle_check[]" value="1" click="calculate_discount(this);"/>
and update the function to:
function calculate_discount(element){
alert($(element).val());
if($(element).is(":checked")){
alert('Hiii');
}
else{
alert('Byeee');
}
}
With this solution you avoid unnecessary jQuery searching.

Get function from input field

I have some jQuery inside a text field which I need to fire, but I'm struggling to get anything to happen.
I think the best way to explain this is to put down some code:
<input type="hidden" id="win-body-tst" value="$("#a").append($("#b"));">
<script> function NNNfoo(){
var funcvar = document.getElementById('win-body-tst').value;
funcvar
}</script>
I am calling NNNfoo() successfully, but the append does not action.
eval will run JS code which is expressed as a string (but I'd take a step back and try to solve whatever problem you have another way, it isn't usually a good idea to ask users to input JS).
eval(funcvar);
(You also need to convert your " as data to " so that they don't act as attribute value delimiters).
You can do it with
function NNNfoo(){
var functionBody = document.getElementById('win-body-tst').value;
var func = new Function( functionBody );
func();
}
But why do you want to run arbitrary code from input elements ?

Categories