passing arguments to JavaScript function inside input field vs. from inside function - javascript

What are the pros/cons between the following two ways of passing/setting variables?
<input type="password" name="pw1" id="pw1" onkeyup="return passwordCheck(document.getElementById('pw1'), document.getElementById('pw2'))"/
function passwordCheck(first, second){...
OR
<input type="password" name="pw1" id="pw1" onkeyup="return passwordCheck()"/
function passwordCheck(){
var first = document.getElementById('pw1')
var second = document.getElementById('pw2')...

It makes your html markup easier to read (and your js code). It (moreso) decouples your code from your markup. An even better approach would be to bind an event listener to the input by targeting the id. That way you have NO js in your markup.
edit to respond to comment: I was referring to the 2nd example (calling a function) being better, but overall it's better to do event binding. There are various methods to do it, here is an example:
<input type="password" name="pw1" id="pw1"/>
// ...
document.getElementByID('pw1').onkeyup = function() {
// do stuff
}

Related

JavaScript - how to change field values oninput and onchange

I can't figure out how to change form field values with the oninput or the onchange method. For example, I need to make one input field to change its value as soon as another input field is being changed. So I'm trying:
<input type="number" id="a" value="999.99" oninput="updateInput(value)"/>
<input type="number" id="b" value=""/>
<script>
$(document).ready(function updateInput(value) {
document.getElementById("b").value = document.getElementById("a").value;
});
</script>
It doesn't do anything. What am I doing wrong?
In another case, I need to change the value of a drop-down according to another drop-down (with an if clause). Since the simple script above doesn't work already, I don't even have a clue what to do about the second one...
There are a few issues here; the first one to sort out is where you're declaring your functions. Javascript has a concept of scope, which you can think of as kind of a container for declared variables. The reason your function isn't doing anything is because the definition of updateInput is locked away inside your jquery $(document).ready scope.
Once you take that definition out of the jquery wrapper, it's available to the global window scope - which is the one you're accessing in your oninput. I should point out that there are more flexible/useful ways to put an event listener on something, but what you have will work, if this is a simple use case.
function updateInput(value) {
document.getElementById("b").value = document.getElementById("a").value;
}
<input type="number" id="a" value="999.99" oninput="updateInput(value)"/>
<input type="number" id="b" value=""/>
Your function is undefined in the markup, because it is passed to the ready and scoped there. It will better to not pass the update function to the ready, but create inside it and attach that function to the input from code. Don't get every time the DOM elements, instead get once and use variables to keep them.
Also you have mixed jQuery approach with pure Javascript approach. I think it will be better to use one of them.
With jQuery
$(document).ready( function() {
const aInput = $("#a");
const bInput = $("#b");
aInput.on('input', function () {
bInput.val(aInput.val());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a" value="999.99"/>
<input type="number" id="b" value=""/>
With pure Javascript
window.onload = function() {
const aInput = document.getElementById("a");
const bInput = document.getElementById("b");
aInput.addEventListener('input', function() {
bInput.value = aInput.value;
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a" value="999.99"/>
<input type="number" id="b" value=""/>
You have to define the updateInput() function outside of $(document).ready(), so that you can call it from the rest of your code, otherwise it is only scoped in there.
Secondly, the argument the function takes is never used, so I took the liberty of removing it.
Thirdly, to call this function as soon as the page is loaded, just call it inside $(document).ready() and you are good to go.
Here's a working example:
function updateInput() {
document.getElementById("b").value = document.getElementById("a").value;
}
$(document).ready(updateInput());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="a" value="999.99" oninput="updateInput()" />
<input type="number" id="b" value="" />

Cannot hide/unhide button inside form

I am not able to unhide a button inside a form. Outside the form it is working.
Also, is there a better way to easily do what I am trying?
<script>
function action() {
document.getElementById('hidden').style.visibility = 'visible';
}
</script>
<input type="text" onChange="action();" id="textfield" name="textfield" />
<input type="button" style="visibility: hidden" id="hidden" value="i am here" />
I try to be careful with id names that I don't accidentally use key words with the id name. Try changing the id="hidden" to id="btnIAmHere". Also action is already a method of a form.
Another way to hide something is to set style.display="none". To make it visible again, set style.display="block"
The difference between these two ways to make something invisible is that setting the visibility doesn't remove the space the object took up.
just call the method like this :
<input type="text" onChange="window.action();" id="textfield" name="textfield" />
I'm not sure but I think it's because the scope is not the same.
See the fiddle
That is due to the function name action(). May be the <form> confuses the function name -action with the form attribute- action. Thus, to make it working, just rename the function to action1() for example and it will work.
See the js
function action1() {
document.getElementById('hidden').style.visibility = 'visible';
}

How to remove an event listener via Chrome extension

I need to remove the following event listeners with my Chrome extension, after the page loaded.
Page content:
<input type="password" size="15" value="" autocomplete="off"
onkeyup="javascript:vaciar(this)"
onkeypress="javascript:vaciar(this)"
onkeydown="javascript:vaciar(this)" name="password"
id="contrasena" />
The code in my content script is:
var password_field = document.getElementById("contrasena");
password_field.removeAttribute("onkeypress");
password_field.removeAttribute("onkeydown");
password_field.removeAttribute("onkeyup");
password_field.onkeypress = null;
password_field.onkeydown = null;
password_field.onkeyup = null;
For some reason, the event listeners keep active, but when I copy and execute the code in the console it works.
This fails because of the isolated context that context scripts live in.
To affect handlers set by the page's context, you need to inject the above code into the page.
See this question for a canonical explanation and examples.
Are you putting your reset code in a body/onload function?
‹body onload="resetInput();"›
‹input type="password" size="15" value="" autocomplete="off" onkeyup="vaciar(this)" onkeypress="vaciar(this)" onkeydown="vaciar(this)" name="password" id="contrasena" /›
‹/body›
And declare the function
function resetInput(){
var password_field = document.getElementById("contrasena");
password_field.removeAttribute("onkeypress");
password_field.removeAttribute("onkeydown");
password_field.removeAttribute("onkeyup");
}
You don't need to unbind your event while they are inline events.

How to check inputs in <form> and send form correctly

I have 2 questions:
How to check input better? I have idea:
First, make field near input.
<input type='text' name='firstname'><label id='firstnameError'></label>
Second, call js-function on input onBlur with id of input and id of this label.
<input type='text' name='firstname' id='firstname' onBlur='checkEmpty("firstname", "firstnameError");'><label id='firstnameError'></label>
And js-script:
function checkEmpty(fieldId, errorFieldId)
{
var data = document.getElementById(fieldId).value;
if (data == "")
{
document.getElementById(errorFieldId).innerHTML="Error, input something!...";
}
}
And I will just use this function on all inputs, right?
Is it correct?
How to check all inputs in form correctly?
Sure I can set type=button and onSubmit call some function, which will check all elements in this form. ~ Same function like in first question, but with 5-7 if-blocks for each input. And yes for 10 forms, I will have to write 10 functions, etc. How better do it? Seems to me, I can only send form Id/name and get childs of element. Am I correct?
Maybe another way? I use jquery on my site anyway (some ajax). Maybe it is easier to do what I want on jquery? The problem is I am not too good in js, to use jquery easily. What do you think?
If you just want to verify if some data is provided or not, you can use required attribute.
<input type="text" name="username" required>
if you are using XHTML it should be as shown below..
<input type="text" name="username" required="required">
The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome and is not supported in Internet Explorer 9 and earlier versions, or in Safari.
In case if you want to use JavaScript. You can create a javascript function which will be called on submit of the form.
<form name="search" onsubmit="return validate()" >
Name: <input type="text" name="name"/>
Age: <input type="gender" name="sex"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
function validate(){
// all the code for verification
return false; // if any of the step verification step fails. Otherwise return true.
}
Source: http://www.w3schools.com/tags/att_input_required.asp
To improve on your design, it's better to use non-inline JavaScript. Try using a design like this:
var fname = document.getElementById("firstname");
var other = document.getElementById("otherid");
fname.onblur = other.onblur = function() {
checkEmpty(this.id,this.id+"Error");
}
This will give all your desired elements the same onclick function and eliminate those pesky onblur attributes.
Edit: make sure your variables are declared before you chain assignments like this, or you will yield unwanted global variables.

Make readonly using getElementByName? [duplicate]

This question already has answers here:
JavaScript getElementByName doesn't work
(4 answers)
Closed 9 years ago.
I need to make "readonly" a text field by place javascript code inside external JS file. I can't modify html directly because the page is located on remote server..but I can interact by adding code in external JS who is located on my own host.
The html is this:
<form id="newunitform" class="left" action="page.php" style="width:600px" method="post">
<fieldset>
<ul>
<li>
<label for="add">
<input type="text" value="" name="add">
<input type="hidden" value="" name="remove">
<input type="hidden" value="105" name="resource_id">
<input type="hidden" value="" name="editid">
</li>
</ul>
<label for="submit"> </label>
<input class="button" type="submit" value="Add name" name="submit">
</fieldset>
</form>
I tried several combination such this:
document.getElementByName('add').readOnly=true;
or this:
var add = document.getElementByName('add');
add.readOnly = true;
or this:
document.getElementById('newunitform');
document.getElementByName('add').readOnly=true;
but none work.
As Rocket Hazmat suggests in the comment to your question, you should use
document.getElementsByName('add')[0].readOnly=true;
document.getElementsByName('name')
returns an array. You need to use brackets or .item() to point to your element.
I suggest you using this one, in my opinion it is a better solution:
var newUnitForm = document.getElementById('newunitform');
newUnitForm.add.readOnly = true; //or newUnitForm['add'], it's the same
That's true -- it's either getElementById (single element) or getElementsByName which access all the elements in the DOM that have the name you're looking for.
Once you change Element to Elements you should be able to set the readOnly attribute.
You could also try, document.getElementByNames('someElement').disabled = true; but be careful if there are multiple elements with the same name.
Also -- because syntax like this has tripped me up any number of times, if a function doesn't work as expected, I'll make sure I'm getting the object I think I'm getting by alerting some aspect of the element.
e.g. alert(document.getElementsByName('someElement').length) or alert(document.getElementsByName('someElement').name)
Good luck
If you know there is only one element named "add", you can try something like this:
var elem = document.getElementsByName("add")[0];
elem.setAttribute("readonly", "true"); // or elem.readOnly = true;
If you know there is only one element named "add" inside the "newunitform" form, use LightStyle's suggestion:
var elem = document.getElementById("newunitform").add;
elem.setAttribute("readonly", "true"); // or elem.readOnly = true;
In any case, make sure the snippet is executed after the element in question has been rendered (e.g. you could place it in body's onload method.

Categories