innerHTML won't change element - javascript

I have an div element ("main") on my page who's contents changes back and forth between two different screens (their id's are "readout" and "num"), the contents of which are stored as hidden div elements (using display:none). Each screen has a button which sets mainto the other hidden div.
Since I struggled to get javascript to put num.innerHTML into main on load, I've ended up putting virtually identical content to num (with a different form name) into main:
<p>Number of Passengers per Carriage:</p>
<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="setPassengers();">
<input type="text" name="numApples" id="numPassengers" />
<br/><br/>
<input type="submit" name="Submit" value="OK!"/>
</form>
setPassengers() successfully sets main's contents to readout. readout successfully sets main's contents to num (virtually identical to the original content of main). But then it won't go back to readout.
Here are setPassengers() and setPassengersAgain(), which is the same but for a different form name:
function setPassengers()
{
passengers=document.applesForm.numPassengers.value;
document.getElementById('main').innerHTML=readout.innerHTML;
}
function setPassengersAgain()
{
passengers=document.applesFormAgain.numPassengers.value;
document.getElementById('main').innerHTML=readout.innerHTML;
}
So my question is:
1)Why isn't num changing to readout?
2)Is there a way to load num straight away on page load so as to simplify the code?
EDIT: I can use onload, which means that num is the only bit that's broken...
EDIT 2: Here are the hidden div's:
<div id="readout" style="display:none">
<p>Throughput per hour:</p>
<p id="output">--</p>
<p>Average Dispatch Time:</p>
<p id="avDisTime">--</p>
<form method="post" action="javascript:void(0);" name="dispatchForm" onSubmit="dispatch();i++;">
<input type="submit" name="Submit" value="Press on Dispatch!"/>
</form>
<br/>
<form method="post" action="javascript:void(0);" name="resetTimesForm" onSubmit="resetTimes();">
<input type="submit" name="Submit" value="Reset Times"/>
</form>
<form method="post" action="javascript:void(0);" name="resetAllForm" onSubmit="resetAll();">
<input type="submit" name="Submit" value="Reset All"/>
</form>
</div>
<!--back to default page-->
<div id="num" style="display:none">
<p>Number of Passengers per Carriage:</p>
<form method="post" action="javascript:void(0);" name="applesFormAgain" onSubmit="setPassengersAgain();">
<input type="text" name="numApples" id="numPassengers" />
<br/><br/>
<input type="submit" name="Submit" value="OK!"/>
</form>
</div>

You didn't post your HTML code, so I don't know how it looks like, but you could use somethin like:
HTML:
<button id="changeMain">Change #main</button>
<div id="main">
<div id="readout" class="screen show">
Readout
</div>
<div id="num" class="screen">
Num
</div>
</div>
CSS:
#main>.screen{display:none;}
#main>.screen.show{display:block;}
JavaScript:
var els=[document.getElementById('readout'),document.getElementById('num')],current;
function addClass(el,c){
var arr=el.className.split(' ');
if(arr.indexOf(c)>-1){return;}
arr.push(c);
el.className=arr.join(' ');
}
function delClass(el,c){
var arr=el.className.split(' ');
var i=arr.indexOf(c);
if(i===-1){return;}
arr.splice(i,1);
el.className=arr.join(' ');
}
document.getElementById('changeMain').onclick=function(){
if(!current){
for(var i=0,l=els.length;i<l;i++){
if(els[i].className.indexOf('show')>-1){
current=i;
break;
}
}
}
delClass(els[current],'show');
current=(current+1)%els.length;
addClass(els[current],'show');
}
DEMO: http://jsfiddle.net/CUgqh/
Explanation:
If you want some content insode #main, you should place inside it (hidden or shown). Then, we hide all .screen with #main>.screen{display:none;} except .screen.show: #main>.screen.show{display:block;}.
Then, JavaScript code:
First we create an array with the elements:
var els=[document.getElementById('readout'),document.getElementById('num')],current;
And a function which adds/removes a class c to the element el:
function addClass(el,c){
var arr=el.className.split(' ');
if(arr.indexOf(c)>-1){return;}
arr.push(c);
el.className=arr.join(' ');
}
function delClass(el,c){
var arr=el.className.split(' ');
var i=arr.indexOf(c);
if(i===-1){return;}
arr.splice(i,1);
el.className=arr.join(' ');
}
And we create an event to the button:
document.getElementById('changeMain').onclick=function(){
if(!current){
for(var i=0,l=els.length;i<l;i++){
if(els[i].className.indexOf('show')>-1){
current=i;
break;
}
}
}
delClass(els[current],'show');
current=(current+1)%els.length;
addClass(els[current],'show');
}
The code above does:
If it's the first time the current els' index (current) is undefined, we search which element has the class show by default.
It removes the class show to the current shown element, so it disappears.
It adds 1 to current (or it becomes 0 if it was the last els' element
It add class show to the current element, so it appears.

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/

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;
}

pass values from separate divs into a javascript function

I have a form that has three separate divs within it.
<form method="post">
<div id = "f1">
<div class="label">Value 1:</div>
<input type="text" name="name"/>
<button id = "next1" type="button" onclick="checkValue()">Next</button>
</div>
<div id ="f2">
<div class="label">Value 2:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
<div id ="f3">
<div class="label">Value 3:</div><br>
<input type="text" name="name"/>
<button type="button" onclick="checkValue()">Next</button><br>
</div>
</div>
</form>
In my javascript function. I have a fadein and fadeout attached to each div when the next button is pressed. When the "next1" button is pressed the first div will be faded out and the second div will fade in. I want to check the values inputted in the first div when the user presses the first next button. I know how to do this if i just passed in the whole form into my javascript function on the final submit button, but I would like to know how to do this after each next button is pressed.
I also will have more than one value in each of the divs (f1, f2, f3) but for simplicity I only included one value.
EDIT*: further explaintaion
If i did this by passing in the form into checkValue. I could just do an onsubmit = "checkValue()". And then in my JS file, I would just include checkValue(form) as its parameter. If i want to do a check after every single button is pressed, I am not sure how to do this or what to pass in as its parameter.
Simple mock up hopefully to get you one your way.
Fiddle: http://jsfiddle.net/AtheistP3ace/krr3tgLx/1/
HTML:
<form method="post">
<div id="f1" style="display: block;">
<div class="label">Value 1:</div>
<input type="text" name="name" />
<button id="next1" type="button" onclick="checkValue(this)">Next</button>
</div>
<div id="f2">
<div class="label">Value 2:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
<div id="f3">
<div class="label">Value 3:</div>
<br>
<input type="text" name="name" />
<button type="button" onclick="checkValue(this)">Next</button>
<br>
</div>
</div>
</form>
JS:
function checkValue (button) {
// Finds the sibling input of the button
var input = $(button).siblings('input');
// Gets input value
var value = input.val();
// Stops showing next div if no value
if (value == '') {
return false;
}
else {
// Finds the parent div holding button and input
var div = $(button).closest('div');
// Fades out current div
div.fadeOut();
// Gets next div and fades it in
div.next().fadeIn();
}
}
CSS:
form > div {
display: none;
}
From my assumptions this is what you are looking for :
Multipart form handler
Basically I wired up each button with a class
<button id = "next1" type="button" class="check-btn">Next</button>
Then I used Jquery to get all those buttons and find the parent div (based on your structure) and then get all the child inputs (can include selects etc). From here you can continue to tweak to perform a check on each type of input etc.
$(document).ready(function(){
$('.check-btn').on('click',function(){
var parent = $(this).parent('div');
var elems = parent.find('input');
alert(elems.length);
//DO checks here for each element
});
});

find form id div is in

Bit of a weird question. I have got a form and inside this form the controls are div's with onClick events instead of buttons. I can't use buttons as I can't use page reloads, instead I have to send all data using ajax.
Plus half of the buttons just increase counters, below is my code. How would I go about using JavaScript to find the form ID that the element clicked on is in. So as an example:
<form id="20">
...
<div onClick="doSomething(this)">
...
</form>
The doSomething will then keep moving up levels of parents or something like that until it finds the form, and then a variable will have the form id assigned to it.
<form id="50">
<div class="image_container background">
<div style="text-align:center; font-size:12px;">image1</div>
<input type="hidden" id="imgId" value="50" />
<div class="image" style="background-image:url(images/image3.JPG);"></div>
<div class="selected_product">
<span>KR</span>
</div>
<input type="hidden" id="applied_products" value="KR" />
</div>
<div class="controls_container background">
<div id="selected">KR</div>
<a class="button arrow expandProducts">
<span>
<div class="products">
<span>KR</span>
<span>A5</span>
<span>CC</span>
</div>
</span>
</a>
<hr />
<span class="button plus" onClick="sale(this)"></span>
<input type="text" id="amount" disabled="disabled" value="0"/>
<span class="button minus"></span>
<hr />
<input type="text" id="total" disabled="disabled" value="£0"/>
</div>
</form>
Your doSomething function could continue navigating through it's parents until it finds a form, like so:
function doSomething( elem )
{
var parent = elem.parentNode;
if( parent && parent.tagName != 'FORM' )
{
parent = doSomething(parent);
}
return parent.id;
}
Also, if you use <button type="button">...</button> it won't cause a page refresh, since the default button type is submit.
If you are going straight javascript and not jquery or some other library. Each DOM Element has a parentNode Property
var elm = document.getElementById(yourDivId);
var parent = elm.parentNode;
From there you can cycle through each parent, until you get back to the form element and then pull out the id.
How about something like that:
function handler(target) {
var parent = target.parentNode;
// loop until parent is a form or browser crashes :)
while (parent.tagName != 'FORM') {
parent = parent.parentNode;
}
var formId = parent.id; // the id you wanted
// do stuff
}

How to get the index of an element without 'this'?

I have a form that looks kind of like this:
<div>
<div class="contact">
<h1>Person's name</h1>
<!-- more stuff goes here -->
<form method="post" action="myurl">
<input type="submit" value="go" />
</form>
</div>
<div class="contact">
<h1>Another name</h1>
<!-- more stuff goes here -->
<form method="post" action="myOtherUrl">
<input type="submit" value="go" />
</form>
</div>
</div>
I'm using jQuery to capture the form's submit event and need to get the index of the div containing the button that submitted it. Normally I'd use jQuery's index() function like so:
var i = $(this).parents('.contact').index(this);
Unfortunately, the this operator in this case refers to the form that is being submitted. I think there's probably something simple I'm missing, but my mind's drawing a blank on this one.
Keep it simple:
var parent = $(this).closest('div.contact'); // get containing DIV
var i = $('div.contact').index(parent); // get index relative to the rest
var i = $(this).parents('.contact:first').prevAll('.contract').length

Categories