How to apply onfocus function to all "input" objects? - javascript

I'd like to create an onfocus function to my input fields in a form. I'm working with a drag and drop landing page wizard(in Marketo) therefore I don't have access to the HTML tags.
I tried to do use getElementById and it worked only on the first field. I also tried the following:
<script>
var input = document.getElementsByTagName('input')[0]
input.onfocus = function() {
this.value=''
}
</script>

You query for all the <input>s elements, but work only with the first match:
var input = document.getElementsByTagName('input')[0]
Iterate over all the matches and do your magic:
var inputs = document.getElementsByTagName('input');
for (var i=0; i< inputs.length; i++){
inputs[i].onfocus = function(){this.value = '';};
}
If you can use jQuery, it's a lot easier:
$('input').focus(function(){this.value = '';});

Another variant would be this
//get all inputs
var inputs = document.getElementsByTagName('input')
//cache the length
, inputsLen = inputs.length;
//define one handler
function focusHandler(){
this.style.backgroundColor = 'red';
}
//loop through all
while(inputsLen--){
//each element's onfocus references only one function instead of "one each"
inputs[inputsLen].onfocus = focusHandler;
}

yea ,in jquery you can do it like:
$("input").on("focus",function(){
//function data block goes here
});

Everyone beat me to it but try this
$("input").on("focus",function()
{
this.value=''
});

Related

Create options onClick attribute

This is the idea: When I click on "word1" (or "word2") the select tag shows me the options. Once I click on one of the options, my script change "word1" (or "word2") whit the option. I can update the options, but once I click on one of them the script always write the last option.
The script write the same onClick attribute for all the options...
I've been searching a lot but I cannot understand why it happen, and how to solve it.
Here is the code:
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
option.onclick = function() {
currentElement.innerHTML = newWord;
};
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
Thanks in advance
You can not bind 'click events' on 'options' property of a 'select box'. You will need to bind a onchange event listner on the 'select element'. Inside the callback function of the change event listner put your code logic for updating word text. As the 'change' event listner is not in the scope of 'updatemyselect' function, you can store the last clicked element in a variable and use the same in the callback function for updating the desired word text. Please refer to the below code which I have edited.
var clickedElement;
function updatemyselect(currentElement, optionsList) {
clickedElement = currentElement;
var mySelect = document.getElementById("mySelect");
var i;
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i]
option.text = newWord;
/*option.onclick = function() {
currentElement.innerHTML = newWord;
};*/
mySelect.add(option);
}
}
document.getElementById("mySelect").addEventListener("change", updatePTag);
function updatePTag(){
clickedElement.innerHTML = this.value;
};
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" class="changedWord">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" class="changedWord">Word2</p>
The reason why you are always getting the last option value is because you are using the newWord variable in your onclick function instead of an actual value, or reference to the currently selected option.
As a result, after you have finished going through the loop, the value of newWord is always equal to the last option text, so, regardless of which option is selected, when you are returning newWord, you will get the same value (i.e., either, "Fish" or "Whale").
Instead, try using currentElement.innerHTML = mySelect.value; in the onclick function.
First you need to set the value attribute on each option.
After you can use the onChange event on Select to display your value.
You can use Jquery to do this, its more easy
jquery select change event get selected option
Thanks to everybody.
I didn't realize that currentElement.innerHTML = newWord; was actually giving the value of the same variable to every onClick attribute.
I finally solved in this way, even if I think the solution of Arun Singh is better.
function updatemyselect(currentElement, optionsList) {
var mySelect = document.getElementById("mySelect");
var i;
mySelect.onchange= function() {currentElement.innerHTML=mySelect.value;};
//Clear the options
mySelect.options.length = 0;
//Add the options
for (i = 0; i < optionsList.length; i++) {
var option = document.createElement("option");
var newWord = optionsList[i];
option.text = newWord;
mySelect.add(option);
}
}
<select id="mySelect">
</select>
<p onclick="updatemyselect(this,['Dog','Cat','Fish'])" value="a">Word1</p>
<p onclick="updatemyselect(this,['Cow','Horse','Whale'])" value="b">Word2</p>

Dynamical Calculator Javascript

It is a calculator which has spans from which I want to take a values(1,2,3, etc.) and two fields: First for displaying what user is typing and the second is for result of calculation.
The question how to get values so when I click on spans it will show it in the second field
Here is the code.
http://jsfiddle.net/ovesyan19/vb394983/2/
<span>(</span>
<span>)</span>
<span class="delete">←</span>
<span class="clear">C</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span class="operator">÷</span>
....
JS:
var keys = document.querySelectorAll(".keys span");
keys.onclick = function(){
for (var i = 0; i < keys.length; i++) {
alert(keys[i].innerHTML);
};
}
var keys = document.querySelectorAll(".keys span");
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function(){
alert(this.innerHTML);
}
}
keys is a NodeList so you cannot attach the onclick on that. You need to attach it to each element in that list by doing the loop. To get the value you can then simple use this.innerHTML.
Fiddle
This should get you started.. you need to get the value of the span you are clicking and then append it into your result field. Lots more to get this calculator to work but this should get you pointed in the right direction.
Fiddle Update: http://jsfiddle.net/vb394983/3/
JavaScript (jQuery):
$(".keys").on("click","span",function(){
var clickedVal = $(this).text();
$(".display.result").append(clickedVal);
});
You can set a click event on the span elements if you use JQuery.
Eg:
$("span").click(
function(){
$("#calc").val($("#calc").val() + $(this).text());
});
See:
http://jsfiddle.net/vb394983/6/
That's just to answer your question but you should really give the numbers a class such as "valueSpan" and the operators a class such as "operatorSpan" and apply the events based on these classes so that the buttons behave as you'd expect a calculator to.
http://jsfiddle.net/vb394983/7/
var v="",
max_length=8,
register=document.getElementById("register");
// attach key events for numbers
var keys = document.querySelectorAll(".keys span");
for (var i = 0; l = keys.length, i < l; i++) {
keys[i].onclick = function(){
cal(this);
}
};
// magic display number and decimal, this formats like a cash register, modify for your own needs.
cal = function(e){
if (v.length === self.max_length) return;
v += e.innerHTML;
register.innerHTML = (parseInt(v) / 100).toFixed(2);
}
Using JQuery will make your life much easier:
$('.keys span').click(function() {
alert(this.innerHTML);
});

Can I get the html element in an event trigger function in javascript?

Edit: I need to mention that I do not want to use jQuery.
This is my code. I need to access the element which triggered the event such that I don't have to make two different functions for each html element.
document.getElementById("login").onmouseover = turnWhite;
function turnWhite(e){
}
I need maybe something like this. Don't know if it's possible though.
function turnWhite(e){
e.HTMLEL.style.color = "white";
}
Is this possible?
According to javascripter.net
e.srcElement in Internet Explorer
e.target in most other browsers.
If you wanted to apply the same event function to a set of elements, you could try something like this:
var buttons = document.getElementsByClassName("change");
for(var i = 0;i < buttons.length;i++){
buttons[i].onmouseover = function(){
this.style.color = "red";
}
}
Demo: http://jsfiddle.net/louisbros/rt24U/
You should be able to use e.target or e.currentTarget. However, behavior seems to be different per browser... Best to use a library like jquery or yui. Here is some documentation.
Here is the JSFiddle so you can play with it: http://jsfiddle.net/9nr4Y/
HTML:
<div class="login">Login</div>
<br />
<div class="login">Login 2</div>
JavaScript:
(function() {
var elms = document.getElementsByClassName("login"),
l = elms.length, i;
for( i = 0; i < l; i++ ) {
( function( i ) {
elms[i].onmouseover = function() {
this.style.color = "#000000";
this.style.background = "#FFFFFF";
};
})(i);
( function( i ) {
elms[i].onmouseout = function() {
this.style.color = "#FFFFFF";
this.style.background = "#000000";
}
})(i);
}
})();
Create a self-invoking function that then gets the elements by a class name. The reason for this is because you don't really want to have more than one element with the ID anyway. Getting the class name will generate an Array of items that have that class. Then you can iterate over the new array and assign the event to each one of them.
Then we're getting each individual element with "this" instead of the actual event.
For reference:
How to get current element in getElementsByClassName
You could also go with this non-standard cross-browser hack:
document.getElementById("login").onmouseover = function () { turnWhite(); }
function turnWhite(){
var myEventElement = turnWhite.caller.arguments[0].target;
//do something with myEventElement
}
Useful if you want to avoid passing parrams.
Demo: http://codepen.io/mrmoje/pen/avbEm

How to remove style one click event?

How can i remove the style class applied to a textbox on the click event? I'm calling the textbox element using getElementsByName(). Here's my code:
<input id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
function clearText(element)
{
id = element.getAttribute("id");
var textElement = document.getElementById(id);
textElement.value = "";
var element = document.getElementsByName("popUpText");
var count = 0;
for (count = 0; count < 2; count++) {
var id = element.item(count);
id.classname = "";
}
}
In the above script, im not getting the id in the variable id. Right now the values are like "#inputTextBoxName". Please help.
you can use removeClass();
you can manege your styling using attr();
exp:
$("#yourid").attr("style","float: right");
or remove class using
$("#yourid").removeClass("yourClass");
It is case sensitive so
id.className = '';
If you're trying to remove the class from the textbox when you click on the textbox itself, that code is far, far longer than it needs to be.
HTML:
<input type="text" id="userNameExists" name="popUpText" class="pop-upText" onclick="clearText(this);" />
Javascript:
<script>
function clearText(element) {
element.className = '';
element.value = '';
}
</script>
That said, inline event handlers (ie. declaring an onclick attribute on your HTML element) are a bad practice to get into.
Also, if you pass in a reference to an element, get its id, then call document.getElementById() with said id, you end up with two references to the same element. Yes, it should work, but totally pointless.

Get all form tags with javascript/jQuery?

Is there any such function to get all form tags?
by form tags I mean all <input>, <select> etc?
Thanks
You could use jquery:
$(':input')
Otherwise, given the id of the form, all of its fields are given by
var formid = "foo";
var myform = document.getElementById( formid )
if (myform != null) {
// myform.elements is an array of the fields
}
And if you just wanted to find all the select elements in the page, use getElementsByTagName()
var all_selects = document.getElementsByTagName('select')
Using jQuery the following will make them pink:
$("input, select, textarea").css({background: "pink"});
var elements = getElementsByTagName("input")
.splice(getElementsByTagName("select"));
// splice to your hearts content
A framework is overkill for this:
document.getElementsByTagName("input")
document.getElementsByTagName("select")
function getFormElements() {
var ary = [];
// use the full list of supported form elements below if this is not exhaustive
var elementNames = ['input','select','textarea','button'];
for (var i=0; i < elementNames.length; i++) {
ary.concat(document.getElementsByTagName(elementNames[i]));
}
return ary;
}

Categories

Resources