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.
Related
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.
I'm trying to assign a value to a hidden form field, the value comes from a query string parameter. The function to extract the query string parameter works fine, however the function to assign the variable (using document.forms) to the hidden form field value attribute doesn't seem to work, the value is empty if I inspect element, however it works if I run it through the console in Chrome. Many thanks.
Get variable from function that finds query string:
var actionCode = getAllUrlParams().actioncode;
Set hidden form field value:
function setHidden()
{
document.forms[0].action.value += actionCode;
return true;
}
Form HTML:
<input id="field25" name="action" type="text" value="" class="field-size-top-large" disabled="disabled">
Live page is here: http://exhibit.ubm-events.com/LP=83?cid=sm(n)_VIS_DRV20180515%7C1&actioncode=EMA1234
pass the actionCode variable to the function so that it's definitely in scope, and use .getElementById seeing as the element has an ID.
function setHidden(actionCode)
{
document.getElementById("field25").value += actionCode;
return true;
}
Try below code
function setHidden(a,b){
return a*b;
}
document.getElementById('field25').value = setHidden(2, 3);
you need to select the element using jquery and assign the value to it
$("#field25").val("your value")
Ref http://api.jquery.com/val/#val2
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. ;)
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).
This is driving me nuts, and I'm sure it's both possible and surely simple to do.
I have a page with a whole bunch of dynamically created forms on it. In one of my functions, I need to access one of those forms, so I pass the name of the form in a variable.
Then I need to access the name of that form using the document tree.
However, when I put in the variable, it assumes the name of the variable is the name of the form.
So this does not work:
function myAwesomeFunction(nameOfForm)
{
var selection = document.nameOfForm.nameOfInput.selectedIndex;
}
So I looked around the net and saw that I need to use bracket notation, but this doesn't work either:
function myAwesomeFunction(nameOfForm)
{
var selection = document[nameOfForm].nameOfInput.selectedIndex;
}
I also tried with some quotation action:
function myAwesomeFunction(nameOfForm)
{
var selection = document['nameOfForm'].nameOfInput.selectedIndex;
}
... but no joy.
So, where am I going wrong?
For bonus points... what if both the name of the form and the name of the particular input were both dynamic? Then what?
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document[nameOfForm][nameOfInput].selectedIndex;
}
Look them up in the forms object - this won't work since it is an array and not an object.
use document.getElementsByName
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var selection = document.getElementsByName(nameOfForm)[nameOfInput].selectedIndex;
}
or even better, set an id attribuite on the form and use document.getElementById to find the form
Try using document.getElementById(nameOfForm) (if you have the ID on the form as well)...
If you can include a jQuery reference to your page, you can easily do the following (again assuming you have the ID on the form):
function myAwesomeFunction(nameOfForm, nameOfInput)
{
var form = $("form#" + nameOfForm);
var input = $("#" + nameOfInput + ":input");
var selection = $(input).val();
}
function focusElement(formName, elemName) {
var elem = document.forms[formName].elements[elemName];
}
try this
formname is name of the form and elemname is input label name