Why can't select label with document.forms? - javascript

Is it possible to get label or div with document.forms ?
If yes. how ?
If not. Why ?
When I try it gives "undefined";
Example Code:
<form name="form1">
<div id="div1">
<label id="label1" for="uname">Username: </label>
<input type="text" id="uname" name="username" >
<button id="button1" onclick="func1()" >Okay!</button>
</div>
</form>
<script>
var form=document.forms['form1'];
function func1() {
event.preventDefault(); // -
console.log(form["uname"]); // gives input element
console.log(form["button1"]); // gives buttonn element
console.log(form["label1"]); // undefined
console.log(form["div1"]); // undefined
// I can get them like :
console.log(form["uname"].previousElementSibling); // gives label element
console.log(form["uname"].parentElement); // gives div element
// ...etc
// but, the questions is why I can't with document.forms
}
</script>

You can't select div because div are not part of form element. Source
var form=document.forms['form1'];
function func1() {
event.preventDefault(); // -
console.log(form["uname"]); // gives input element
console.log(form["button1"]); // gives buttonn element
console.log( form["uname"].labels[0] )
console.log(form["div1"]); // cant select div, because div are not form element
// I can get them like :
console.log(form["uname"].previousElementSibling); // gives label element
console.log(form["uname"].parentElement); // gives div element
// ...etc
// but, the questions is why I can't with document.forms
}
<form name="form1">
<div id="div1">
<label id="label1" for="uname">Username: </label>
<input type="text" id="uname" name="username" >
<button id="button1" onclick="func1()" >Okay!</button>
</div>
</form>

Content elements contained within a form have no relevance to the form being processed for being valid or submitted so there is no reason those content elements would need to be part of the form object.
You can however use form.querySelector() to target them
const form = document.forms.form1,
label = form.querySelector('#label1');
console.log('Label text = ', label.textContent)
<form name="form1">
<div id="div1">
<label id="label1" for="uname">Username: </label>
<input type="text" id="uname" name="username" >
<button id="button1" onclick="func1()" >Okay!</button>
</div>
</form>

It looks like form[elementId] returns the input element with that id. But that doesn't work as it only works for input elements. What you could do instead is form.elements, this is a HTMLColection which you could use with ids to get elements. form.elements[elementId].
Although that works, I would recomend you use document.getElementById. This way you don't need to understand old html/js jank. You would use it like this:
console.log(document.getElementById("uname")); // gives input element
console.log(document.getElementById("button1")); // gives button1 element
console.log(document.getElementById("label1")); // gives label element
console.log(document.getElementById("div1")); // gives div element

Related

How can I get the source code of a specific div on radio oncheck?

I'd like to get the source code of a div, so example if a div contains some tags I'd like to get them as they are in html format and update it on a textfield.
JsFiddle : https://jsfiddle.net/Lindow/g1sp1ms3/2/
HTML :
<form>
<label class="tp_box_1">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>
<br><hr><br>
<label class="tp_box_2">
<input type="radio" name="selected_layout" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>
<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>
JavaScript :
$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the specific div children of $this
var selected_layout = $(this).find('.selected_layout');
// get source code of what's inside the selected_layout
/* example :
<h3>box_two</h3>
<p>2</p>
and put it in someVariable.
*/
// and put in into textarea (all this need to happens when a radio is changed with the source code of the checked div)
var someVariable = ...
$('textarea').val(someVariable);
}
});
How can I achieve this ? How can I get the source code inside a specific div ?
First, you don't want selected_layout to be equal to: $(this).find('.selected_layout') because this already points to that element. You want it to point to the next element that comes after it.
I think this is what you are looking for:
$('input[type="radio"][name="selected_layout"]').change(function() {
if(this.checked) {
// get the index within the set of radio buttons for the radio button that was clicked
var idx = $("[type=radio][class=selected_layout]").index(this);
// Get the div structure that corresponds to the same index
var test = $("[class^='box_']")[idx];
// Now, just make that the value of the textarea
$('textarea').val(test.innerHTML);
}
});
textarea { width:100%; height:75px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label class="tp_box_1">
<input type="radio" name="selected_layout" id="sl1" class="selected_layout" value="layout_1">
<div class="box_1">
<h3>box_one</h3>
<p>1</p>
</div>
</label>
<label class="tp_box_2">
<input type="radio" name="selected_layout" id="sl2" class="selected_layout" value="layout_2">
<div class="box_2">
<h3>box_two</h3>
<p>2</p>
</div>
</label>
<textarea id="mytextarea"></textarea>
<input id="submit_form" type="button" value="Send">
</form>
Create div element with:
Template inside
class or id for identifying
Set inputs' value to desired template class/id, then on input change find the template element base on input's value and extract the innerHTML of it by using jQuery's .html() method. Then put this HTML as an new value of textarea using also the.html() method on textarea element.
HTML:
<div id="template1" style="display:none;">
<h1>Hi!</h1>
</div>
<input type="radio" onchange="findTemplate(event)" value="template1" />
<textarea class="texta"></textarea>
jQuery:
var findTemplate = function(event) {
var target = $(event.target);
var templateName = target.val();
var template = $("#"+templateName);
var template = template.html();
var textarea = $(".texta");
textarea.html(template);
};
Working fiddle: https://jsfiddle.net/rsvvx6da/1/

Viewing [object HTMLInputElement] - JavaScript

I using javascript to extract the value from the SPAN element, then put it in a hidden form field, and then submit the data but why am I getting this result?
<form onsubmit="CDMFOCT()" id="CDMFOCTform">
<div class="CDMFOCT"></div>
<span class="CDMFOCT-span"></span>
<input type="hidden" name="CDMFOCTtimer" id="CDMFOCTtimer" value="not yet defined">
</form>
Javascript:
function CDMFOCT() {
CronSaati = $('.CDMFOCT-span').html();
$("#CDMFOCTtimer").val(CDMFOCTtimer);
$("#CDMFOCTform").submit();
};
Output:
Time: [object HTMLInputElement] will...
The are two problem in your code
$("#CDMFOCTtimer").val(CDMFOCTtimer); should be replaced with $("#CDMFOCTtimer").val(CronSaati); to give the hidden field value of your span.
you have set CronSaati as a variable. var CronSaati = $('.CDMFOCT-span').html();
So Try this
$("#CDMFOCTform").submit(function() {
var CronSaati = $('.CDMFOCT-span').html();
$("#CDMFOCTtimer").val(CronSaati);
// just for showing the html content of your span has been inserted into hidden input field
alert($("#CDMFOCTtimer").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="CDMFOCTform" method="post" action="">
<div class="CDMFOCT"></div>
<span class="CDMFOCT-span">Hello</span>
<input type="hidden" name="CDMFOCTtimer" id="CDMFOCTtimer" value="not yet defined">
<input type="submit" name="CDMFOCTsubmit">
</form>
Using JavaScript & jQuery to extract the value of span:
var node = $('.CDMFOCT-span')[0].childNodes[0].nodeValue;
Edit: Or just simply:
var node = $(.CDMFOCT-span).text();
Read more about how to get text node of an element in this link
and now putting it in the hidden form field:
$("input#CDMFOCTtimer").val(node);

How to get span element with no id which is inside a div with no id

I have 2 span elements inside 2 div elements. Both span elements have no id and both div elements also have no id.
The 1st div has the 1st input element with an id (id_name) and then have the 1st span element after it.
The 2nd div has the 2nd input element with an id (id_password) and then have the 2nd span element after it.
I have a javascript function which I call on submit of form. Inside that function I can get the 1st input element in a variable element_id_name and the 2nd input element in a variable element_id_password. Now how can I get the 1st span element which comes after 1st input element? And how can I get the 2nd span element which comes after 2nd input element? Since I dont have id for span elements, I cannot use document.getElementById(). Is there a way to get 1st span element by reference to 1st input element?
This is my code:
<html>
<head>
<meta charset="ISO-8859-1">
<title>test</title>
<style type="text/css">
.error_noshow{
display: none;
}
.error_show{
color: red;
}
</style>
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
return false;
}
</script>
</head>
<body>
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
Thank you for reading my question.
var spans = document.getElementsByTagName('span');
span[0] is the first span, span[1] is the second span. However it's not the preferred way to do this. Use jQuery to make it easier or add an id or classname
To access next span element you can use nextElementSibling property.
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
var firstSpan=element_id_name.nextElementSibling;
return false;
}
</script>
But keep in mind that nextElementSibling not working in all version of browsers so you can simulate this using nextSibling http://www.w3schools.com/dom/prop_node_nextsibling.asp;
You can use querySelector to find the elements by their attributes.
function validate() {
var element_id_name = document.querySelector("[name=txt_user_name]");
var element_id_password = document.querySelector("[name=txt_password]");
console.log(element_id_name, element_id_password);
return false;
}
.error_noshow{
display: none;
}
.error_show{
color: red;
}
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
I'm not answering the question because someone already did, but it seems like you want to check if the user typed something in both field, you could skip the javascript and use the HTML5 tag "required" like so
<input type="text" require />.
The user will have an error message if he tries to submit. But keep in mind that old version of IE will skip this check.

JQuery detects focusOut even if I still focus on input inside the same div. How to change it?

This is my code:
Javascript:
$(".test").on("focusout", function (e) {
$("#output").append("Lost focus<br>");
});
HTML:
Inputs inside div:
<div class="test">
<input type="text" />
<input type="text" />
</div><br>
Inputs outside div:<br>
<input type="text" />
<div id="output">
</div>
I want to detect if user leaves "div.test". Unfortunately, "focusout" works also when I move focus to other object inside this div.
Look at this fiddle: http://jsfiddle.net/Piotrek1/wfukje3g/6/
Click on first input and use Tab to switch through textboxes. "
Lost focus" should appear only if user move out from the div, but it happens always. Why is that and how to change it?
The $ operator returns a collection. You have two inputs inside the <div class="test">. So it matches all elements and children with the .test class.
I think what you want two divs with separate input elements and two different classes OR, use an ID on the actual input element so the $ operator only matches the input id you want this event to fire on. http://jsfiddle.net/wfukje3g/7/
$("#test").on("focusout", function (e) {
$("#output").append("Lost focus<br>");
});
<div class="sometest">
<input id="test" type="text" />
<input type="text" />
</div><br>
Inputs outside div:<br>
<input type="text" />
<div id="output">
</div>
I have implemented piece of code to handle div focus out
$(document).ready(function () {
var count = 1;
$("#name").focusout(function (e) {
if($(this).has(e.relatedTarget).length === 0) {
$("#output").append("<label style='width:100%;'>"+ count++ +" Name div focus out </label>");
}
});
});
Inputs inside div:
<div id="name" class="test">
<input type="text" id="firstname"/>
<input type="text" id="lastname"/>
</div>
Inputs outside div:<br>
<input type="text" id="dob"/>
<div id="output" style="width:100%"></div>
In this piece of code I have used relatedTarget.
relatedTarget will provide the next focused element If next element is not the child of this div then it is div focus out.
Try this in your code.
I hope this will be helpful.
Thanks
JSFIDDLE LINK - Sample code

select particular input field name of particular form

i have some html code like this
<form name="first"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
<form name="second"><input name="firstText" type="text" value="General" />
<input name="secondText" type="text" value="General" />
<input name="ThirdText" type="text" value="General" />
<input name="FourthText" type="text" value="General" />
<input name="FifthText" type="text" value="General" />
</form>
i want to select "secondText" of form "second" using jquery or javascript and i want to change value of it using jquery.
Using jQuery:
var element = $("form[name='second'] input[name='secondText']");
Using vanilla JS:
var element = document.querySelector("form[name='second'] input[name='secondText']");
Changing the value: element.val(value) or element.value = value, depending of what you are using.
To the point with pure JS:
document.querySelector('form[name=particular-form] input[name=particular-input]')
Update:
This selector will return the input named "particular-input" inside form named "particular-form" if exists, otherwise returns null.
The selector filter "form[name=particular-form]" will look for all forms with name equals "particular-form":
<form name="particular-form">
The selector filter "input[name=particular-input]" will look for all input elements with name equals "particular-input":
<input name="particular-input">
Combining both filters with a white space, I mean:
"form[name=particular-name] input[name=particular-input]"
We are asking for querySelector(): Hey, find all inputs with name equals "particular-input" nested in all forms with name equals "particular-form".
Consider:
<form name="particular-form">
<input name="generic-input">
<input name="particular-input">
</form>
<form name="another-form">
<input name="particular-input">
</form>
<script>
document.querySelector('form[name=particular-form] input[name=particular-input]').style.background = "#f00"
</script>
This code will change the background color only of the second input, no matter the third input have same name. It is because we are selecting only inputs named "particular-input" nested in form named "particular form"
I hope it's more clear now.
;)
By the way, unfortunately I didn't found good/simple documentation about querySelector filters, if you know any reference, please post here.
// Define the target element
elem = jQuery( 'form[name="second"] input[name="secondText"]' );
// Set the new value
elem.val( 'test' );
Try
$("form[name='second'] input[name='secondText']").val("ENTER-YOUR-VALUE");
You can do it like this:
jQuery
$("form[name='second'] input[name='secondText']").val("yourNewValue");
Demo: http://jsfiddle.net/YLgcC/
Or:
Native Javascript
Old browsers:
var myInput = [];
myInput = document.getElementsByTagName("input");
for (var i = 0; i < myInput.length; i++) {
if (myInput[i].parentNode.name === "second" &&
myInput[i].name === "secondText") {
myInput[i].value = "yourNewValue";
}
}
Demo: http://jsfiddle.net/YLgcC/1/
New browsers:
document.querySelector("form[name='second'] input[name='secondText']").value = "yourNewValue";
Demo: http://jsfiddle.net/YLgcC/2/
You can try this line too:
$('input[name="elements[174ec04d-a9e1-406a-8b17-36fadf79afdf][0][value]"').mask("999.999.999-99",{placeholder:" "});
Add button in both forms. On Button click find nearest form using closest() function of jquery. then using find()(jquery function) get all input values. closest() goes in upward direction in dom tree for search and find() goes in downward direction in dom tree for search. Read here
Another way is to use sibling() (jquery function). On button click get sibling input field values.

Categories