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

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.

Related

Why can't select label with document.forms?

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

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/

Move input between divs

Trying to move user input from one div to another via a move button, back and forth. Even if there is multiple inputs one can move selected input from one to the other.
So far it moves all inputs in "field1" to "field2". Im trying to move only a single line back and forth.
Tried various stuff, still learning this. Any pointers on what i need to look at in order to achieve this?`
Any help appreciated.
var number = [];
function myNotes() {
var x = document.getElementById("field1");
number.push(document.getElementById("input").value);
x.innerHTML = number.join('<input type="button" value="move" onclick="move();"/><br/>');
}
function move() {
$('#field1').appendTo('#field2')
}
form {
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="input" type=text>
</form>
<input type=submit onclick="myNotes();" value="Send">
<br>
<span id='displaytitle'></span>
<h2>Field 1</h2>
<div id="field1"></div>
<h2>Field 2</h2>
<div id="field2"></div>
JSFIDDLE
You've got a mixture of javascript and jQuery going that's kind of hard to understand. I've whipped up an example of this using jQuery, since you seem to have it in your project anyway:
https://jsfiddle.net/j5mvq6L5/7/
HTML:
<form>
<input id="input" type=text>
</form>
<input type=submit id="btnSend" value="Send">
<br>
<span id='displaytitle'></span>
<h2>Field 1</h2>
<div id="field1" class="field"></div>
<h2>Field 2</h2>
<div id="field2" class="field"></div>
JS:
//listen for document ready
$(document).ready(function() {
//button click listener:
$("#btnSend").on("click", function(e) {
var $field1 = $("#field1"); //works like getElementById
//create a containing div for later
var $entry = $("<div></div>").addClass("entry");
//create a new button
var $btnMove = $("<input/>").attr("type", "button").attr("value", "move").addClass("btnMove");
//click listener for the new button
$btnMove.click(function(){
//find "sibling" field (I added a class to both), append this button's parent div
$(this).parents(".field").siblings(".field").append($(this).parent());
});
//append entry parts
$entry.append($("#input").val())
.append($btnMove);
//append entry to #field1
$field1.append($entry);
});
});
CSS:
form {
display: inline;
}
.btnMove {
margin-left: .5em;
}

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

How to show/hide a div with javascript

I'm currently making a registration page for a site and need to show a typical password confirmation message. How would I make a script to hide and show a div?
This is as far as I've got:
<html><head>
<script language="javascript">
function correctpassword()
var password="password"
var confirmpassword="confirmpassword"
if (password1 != password2)
{
showcss="unconfirmed"
}
else
{
showcss="confirmed"
}
</script>
</head>
<body>
<form>
<u>Personal Details</u>
First Name: <input type="text" id="firstname">
Last Name: <input type="text" id="lastname">
Date of Birth:
Gender: Male Female
<u>Login Details</u>
Email Adress:<input type="text" id="email">
Username:<input type="text" id="username">
<!--check avalibility-->
Password:<input type="text" id="password">
Confirm Password:<input type="text" id="confirmpassword">
<!--Javascript if "password" doesnt equal "confirm password" showcss passwords don't match-->
<button type="button" onclick="correctpassword()">Display Date</button>
</form>
</body>
</html>
PS:The variables may be wrong.
Assuming you are talking about hiding / showing a div, spanor other similar element in HTML, you can use the jQuery JavaScript framework. For example:
$('#element_to_show').show();
$('#element_to_hide').hide();
You can trigger the hide / show via events, e.g. key press or user leaving the input element, in jQuery as well.
Control your styles and appearance with className property that applied to class markup attribute.
Try to avoid .style property of the elements and add/remove some classes instead. It will give you more control and simplify maintenance in the future.
in css:
.show{
display:block;
}
.box{
display:none;
}
in html:
<div id="passConfirm"></div>
<div id="box"></div>
in your script:
var confirmEl,
confirmBox;
confirmEl = document.getElementById('passConfirm');
confirmBox = document.getElementById('box');
confirmEl.addEventListener('click', showBox, false);
function showBox () {
confirmBox.className += ' show';
}
As mentioned, you can use some libraries that helps to work with DOM or write your own functions helping to add and remove some classes, check for hasClass method etc.
I'm on my phone, hence the short answer.
Easiest way is to get the id of the element like document.getElementById and place that into a variable.
Then use the style property like
Obj.style.display = "none";
To hide it.

Categories