I try to lern and to transform an HTML CODE(normal code) to javascript unter using the appendChild function atm and i dont understand how it works if i want to create appended parts for an div DOM which is in an div DOM included, because i want to write functions for many many papers ^_^ which i dont want to set it by hand. the problem is, if i try to use the same code under for the other images doesnt take the CSS formats that the images doesnt change it from img1 to img2 to img3 if i klick the right parts. The normal HTML format works fine. any ideas would be cool. thx
What i did: Will see it in the code under //(A). If i try to use it together it doesnt work, and also if i try (A) alone
//--Thats the (normal code) which i want to transform to javascript
<div class="container">
<input type="radio" name="images" id="i1" checked>
<input type="radio" name="images" id="i2" >
<input type="radio" name="images" id="i3" >
<div class="slide_img" id="one">
<img class="img" src="bilder/UE_1_2018.PNG">
<label for="i3" class="pre"></label>
<label for="i2" class="nxt"></label>
</div>
<div class="slide_img" id="two">
<img class="img" src="bilder/UE_2_2018.PNG">
<label for="i1" class="pre"></label>
<label for="i3" class="nxt"></label>
</div>
<div class="slide_img" id="three">
<img class="img" src="bilder/UE_3_2018.PNG">
<label for="i2" class="pre"></label>
<label for="i1" class="nxt"></label>
</div>
</div>
//DIV where the javascript code would be included
<div class="container">
<div id="y2018"></div>
</div>
//Thats my first try to transform it before i write the for functions
<script>
function inputradios(year, divName) {
//---MAIN-ELEMENT---
var element1 = document.getElementById(divName);
//---INPUT---
var para1 = document.createElement("input");
para1.type = "radio";
para1.name = 'images';
para1.setAttribute('checked','checked');
para1.setAttribute("id", "i1");
element1.appendChild(para1);
//---DIV---
var para1_1 = document.createElement("div");
para1_1.setAttribute('class','slide_img');
para1_1.setAttribute("id", "one");
element1.appendChild(para1_1);
//---IMG---
var element2 = document.getElementById(para1_1);
var para1_1_1 = document.createElement("img");
para1_1_1.setAttribute('class','img');
para1_1_1.setAttribute('src','bilder/UE_1' + '_' + year + '.PNG');
element1.appendChild(para1_1_1);
//(A) element2.appendChild(para1_1_1);
//---lABEL 1---
var para1_1_2 = document.createElement("label");
para1_1_2.setAttribute('class','pre');
para1_1_2.setAttribute('for', 'i1' );
element1.appendChild(para1_1_2);
//(A) element2.appendChild(para1_1_2);
//---lABEL 2---
var para1_1_3 = document.createElement("label");
para1_1_3.setAttribute('class','nxt');
para1_1_3.setAttribute('for', 'i1' );
element1.appendChild(para1_1_3);
//(A) element2.appendChild(para1_1_3);
//SAME CODE WITH SOME DIFFERENT CHANGES TO IMPLEMENT IMAGE2,3,...
}
//inputradios(year, NrOfPages, divName);
inputradios(2018, 'y2018');
</script>
I modified your code a bit to make it more clear and consolidated.
If you're working with DOM functions, keep with using setAttribute rather than doing element.id='whatever';, it'll save you frustration later on.
In this example I use loops to create brevity instead of creating basically the same thing over and over.
In the second loop you'll see some nonsense with ? : like (i===0) ? 'one' : (i===1) ? 'two' : 'three'. If you are unfamiliar these are ternary operators which can be used to shortcut if/else blocks.
function inputradios(year, id) {
// I changed divName to id, for clarification an id is not a name
const parentDiv = document.getElementById(id);
// Create INPUTS
// <input type="radio" name="images" id="i1" checked>
// <input type="radio" name="images" id="i2" >
// <input type="radio" name="images" id="i3" >
for (var i=0;i<3;i++) {
const input = document.createElement('input');
input.setAttribute('type', 'radio');
input.setAttribute('name', 'images');
input.setAttribute('id', 'i'+ (i+1));
if (i===0) {
input.setAttribute('checked','checked');
}
parentDiv.appendChild(input);
}
// Create the DIVs
// <div class="slide_img" id="one">
// <img class="img" src="bilder/UE_1_2018.PNG">
// <label for="i3" class="pre"></label>
// <label for="i2" class="nxt"></label>
// </div>
// <div class="slide_img" id="two">
// <img class="img" src="bilder/UE_2_2018.PNG">
// <label for="i1" class="pre"></label>
// <label for="i3" class="nxt"></label>
// </div>
// <div class="slide_img" id="three">
// <img class="img" src="bilder/UE_3_2018.PNG">
// <label for="i2" class="pre"></label>
// <label for="i1" class="nxt"></label>
// </div>
for (var i=0;i<3;i++) {
const div = document.createElement('div');
div.setAttribute('id', (i===0) ? 'one' : (i===1) ? 'two' : 'three');
div.setAttribute('class', 'slide_img');
const img = document.createElement('img');
img.setAttribute('class', 'img');
img.setAttribute('src', 'bilder/UE_'+ (i+1) +'_2018.PNG');
const labelPre = document.createElement('label');
labelPre.setAttribute('for', 'i'+ ((i==0) ? 3 : (i-1)));
labelPre.setAttribute('class', 'pre');
const labelNxt = document.createElement('lable');
labelNxt.setAttribute('for', 'i'+ ((i===2) ? 1 : (i+1)));
labelNxt.setAttribute('class', 'nxt');
div.appendChild(img);
div.appendChild(labelPre);
div.appendChild(labelNxt);
parentDiv.appendChild(div);
}
}
//---IMG---
var element2 = document.getElementById('one');
element1.appendChild(para1_1_1);
//(A)
element2.appendChild(para1_1_1);
Works like a charm :) many thx
Related
I'm trying to create new fields like the first field in this form by clicking on an image, but the fields are spawning below the button to submit and I don't understand why. The behavior I'm looking for is for the new fields to spawn above the button.
Here's my code
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
This is the function:
var element = document.getElementById("add");
element.onclick = function() {
console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.body.appendChild(clone);
}
appendChild, as its name suggests, always appends the new element -- that is, it adds it to the end. What you want is insertBefore:
document.body.insertBefore(clone, ele);
One way to handle this is to wrap your form in a container and append to it :
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').appendChild(clone);
}
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div id="container">
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
I combined the above answers to achieve the expected behavior.
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').insertBefore(clone, ele);
}
I need help extending this JavaScript (borrowed from https://www.quirksmode.org/dom/domform.html):
var appCounter = 0;
function anotherApp() {
appCounter = appCounter + 1;
var newAppField = document.getElementById("keyApp").cloneNode(true);
newAppField.id = '';
newAppField.style.display = 'block';
var newApp = newAppField.childNodes;
for (var i = 0; i < newApp.length; i++) {
var theName = newApp[i].name
if (theName) {
newApp[i].name = theName + appCounter;
}
}
var insertApp = document.getElementById('keyApp');
insertApp.parentNode.insertBefore(newAppField, insertApp);
document.getElementById('appCount').value = appCounter
}
This works fine when element in my form is:
<div id="keyApp" style="display:none">
<input type="text" name="application" id="application">
<input type="text" name="usage" id="usage">
<\div>
But when I add div's around the inputs (bootstrap styling reasons) I loose the ability to update the input names:
<div id="keyApp" style="display:none">
<div class="col-md-2">
<input type="text" name="application" id="application">
</div>
<div class="col-md-2">
<input type="text" name="usage" id="usage">
</div>
<\div>
How do I extend the script to modify the input names in these new div's?
Since there is now another layer, you need to get newApp[i].childNodes[0] now in order to get the actual input elements.
newApp now holds a list of the div elements with col-md-2 styling, and you need to get the children inside of these div elements.
I need some help in editing my current script.
I use 1 radio button, that should hide/display multiple divs when 1 of the radio buttons is selected.
It works fine for just 1 div, but I can not make it work with multiple divs.
My current HTML:
<div class="col-md-12">
<div class="form-group form-group-xl">
<label for="Particulier"><input type="radio" id="Particulier"checked="checked" name="checkzakelijk" onclick="ShowHideDiv()" />Particulier</label>
<label for="Zakelijk"><input type="radio" id="Zakelijk" name="checkzakelijk" onclick="ShowHideDiv()" />Bedrijf</label>
</div>
</div>
<div class="col-sm-6" id="checkzakelijk1" style="display:none;">
<div class="form-group">
<label class="control-label" for="customfield{$customfield.id}">{$customfield.name}</label>
<div class="control">
{$customfield.input} {$customfield.description}
</div>
</div>
</div>
<div class="col-sm-6" id="checkzakelijk2" style="display:none;">
<div class="form-group">
<label class="control-label" for="customfield{$customfield.id}">{$customfield.name}</label>
<div class="control">
{$customfield.input} {$customfield.description}
</div>
</div>
</div>
Current script:
<script type="text/javascript">
function ShowHideDiv() {
var chkYes = document.getElementById("Zakelijk");
var dvPassport = document.getElementById("checkzakelijk");
var dvPassport = document.getElementById("checkzakelijk1");
var dvPassport = document.getElementById("checkzakelijk2");
dvPassport.style.display = chkYes.checked ? "block" : "none";
}
</script>
You are overwriting dvPassport variable, so only the last element will be have its effect.
Change it to
function ShowHideDiv() {
var chkYes = document.getElementById("Zakelijk");
var dvPassport1 = document.getElementById("checkzakelijk");
var dvPassport2 = document.getElementById("checkzakelijk1");
var dvPassport3 = document.getElementById("checkzakelijk2");
var display = chkYes.checked ? "block" : "none";
dvPassport1.style.display = display;
dvPassport2.style.display = display;
dvPassport3.style.display = display;
}
Have a closer look at this bit:
var dvPassport = document.getElementById("checkzakelijk");
var dvPassport = document.getElementById("checkzakelijk1");
var dvPassport = document.getElementById("checkzakelijk2");
What you are doing here is declaring a new variable with the same name multiple times, which doesn't make much sense.
I would suggest jQuery class selector, i.e.
$(".col-sm-6").hide();
Also, in cases where you want to apply something to multiple elements, it's worth giving them the same class, rather than listing the ids. It's simpler and makes the code much more readable.
I have a canvas element containing an image, which is initially a Green Square. I'm trying to change the displayed image based on the input from two sets of jQuery UI radio buttons: the first set allows the user to select a colour and has 3 options (Red/Green/Blue), and the second set allows the user to select a shape (Circle/Square).
My Javascript code declares an array of images, one of which is then assigned to display in the canvas element when a button option is checked, like so:
var images = new Array();
images[0] = new Image();
images[0].src = '../../../media/images/Red-Circle.png';
images[1] = new Image();
images[1].src = '../../../media/images/Red-Square.png';
images[2] = new Image();
images[2].src = '../../../media/images/Green-Circle.png';
images[3] = new Image();
images[3].src = '../../../media/images/Green-Square.png';
images[4] = new Image();
images[4].src = '../../../media/images/Blue-Circle.png';
images[5] = new Image();
images[5].src = '../../../media/images/Blue-Square.png';
$(function () {
$("#colour").buttonset();
$("#shape").buttonset();
});
$('#red').click(function () {
if ($('#red').is(':checked')) {
$("#container #image img").attr("src", images[1].src);
}
});
$('#green').click(function () {
if ($('#green').is(':checked')) {
$("#container #image img").attr("src", images[3].src);
}
});
$('#blue').click(function () {
if ($('#blue').is(':checked')) {
$("#container #image img").attr("src", images[5].src);
}
});
HTML:
<div id="container">
<div id="image">
<img src="media/images/Green-Square.png" />
</div>
</div>
<form>
<div id="colour">
<input type="radio" id="red" name="radio">
<label for="colour1">Red</label>
<input type="radio" id="green" name="radio" checked="checked">
<label for="colour2">Green</label>
<input type="radio" id="blue" name="radio">
<label for="colour3">Blue</label>
</div>
</form>
<form>
<div id="shape">
<input type="radio" id="circle" name="radio">
<label for="circle">Circle</label>
<input type="radio" id="square" name="radio" checked="checked">
<label for="square">Square</label>
</div>
</form>
I've only got as far as being able to select the colour. When it comes to selecting the shape, I want to change the displayed image to retain the previous choice of colour (so that for example, if Red was the currently selected colour and the user then selected Circle, the image displayed would change to a Red Circle and not a Green or Blue Circle). Conversely, if the user selected the shape first and THEN selected a colour, I want the displayed image to retain the choice of shape.
I have a vague idea that the solution might be to do with adding 1 or subtracting 1 from the array index based on what the current index is - but I have no clue how to implement this. I'm relatively new to JS so any help would be appreciated. Thanks.
You can store your images in an 'images' object and access them by string (ex images["RedSquare"]) I've put together a fiddle. The image links are broken but if you inspect the page you can see the src is being changed properly.
https://jsfiddle.net/5wv5ym5p/
HTML:
<div id="container">
<div id="image">
<img src="media/images/Green-Square.png" />
</div>
</div>
<form>
<div class="shape-config" id="colour">
<input type="radio" id="red" name="radio">
<label for="red">Red</label>
<input type="radio" id="green" name="radio" checked="checked">
<label for="green">Green</label>
<input type="radio" id="blue" name="radio">
<label for="blue">Blue</label>
</div>
</form>
<form>
<div class="shape-config" id="shape">
<input type="radio" id="circle" name="radio">
<label for="circle">Circle</label>
<input type="radio" id="square" name="radio" checked="checked">
<label for="square">Square</label>
</div>
</form>
JS (needs JQuery):
var images = {};
images["RedCircle"] = new Image();
images["RedCircle"].src = '../../../media/images/Red-Circle.png';
images["RedSquare"] = new Image();
images["RedSquare"].src = '../../../media/images/Red-Square.png';
images["GreenCircle"] = new Image();
images["GreenCircle"].src = '../../../media/images/Green-Circle.png';
images["GreenSquare"] = new Image();
images["GreenSquare"].src = '../../../media/images/Green-Square.png';
images["BlueCircle"] = new Image();
images["BlueCircle"].src = '../../../media/images/Blue-Circle.png';
images["BlueSquare"] = new Image();
images["BlueSquare"].src = '../../../media/images/Blue-Square.png';
$(function () {
$("#colour").buttonset();
$("#shape").buttonset();
});
$('.shape-config input').click(function () {
var colourId = $("#colour input:checked").attr("id");
var colour = $('label[for='+colourId+']').text();
var shapeId = $("#shape input:checked").attr("id");
var shape = $('label[for='+shapeId+']').text();
$("#container #image img").attr("src", images[colour+""+shape].src);
});
Here is an plunker for what you are trying to do.
https://plnkr.co/edit/jMvjJCxHZzr9dxw5B6RR?p=preview
the function you will require are
$('#circle').change(function () {
if ($('#circle').is(':checked')) {
var a = jQuery.grep(images, function( n ,i) {
if ( n.src == $("#container #image img").attr("src") )
return i;
})[0];
var index = images.indexOf(a);
$("#container #image img").attr("src", images[index-1].src);
}
});
$('#square').change(function () {
if ($('#square').is(':checked')) {
var a = jQuery.grep(images, function( n ,i) {
if ( n.src == $("#container #image img").attr("src") )
return i;
})[0];
var index = images.indexOf(a);
$("#container #image img").attr("src", images[index+1].src);
}
The color select button logic is not correct as well please use this logic there as well.
Why bother using arrays/indexes and storing it at all?
https://jsfiddle.net/0Lqgc3vx/
HTML
<img id="img" src="Green-Square.png" />
<form>
<input type="radio" name="colour" value="Red">
<label for="colour1">Red</label>
<input type="radio" name="colour" value="Green" checked="checked">
<label for="colour2">Green</label>
<input type="radio" name="colour" value="Blue">
<label for="colour3">Blue</label>
</form>
<form>
<input type="radio" name="shape" value="Circle">
<label for="circle">Circle</label>
<input type="radio" name="shape" value="Square" checked="checked">
<label for="square">Square</label>
</form>
JS
$("input[name='colour']").change(function () {
$("#img").attr("src", this.value + "-" + $("input[name='shape']:checked").val() + ".png");
});
$("input[name='shape']").change(function () {
$("#img").attr("src", $("input[name='colour']:checked").val() + "-" + this.value + ".png");
});
hello i am using a form to add experience to users where i have a add more button which adds more (clones) the content and users get one more field to add experience
i am using this code to achieve this
<div id="append_palllsjjs"><div class="full_exp_9092k" id='duplicater'>
<div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Company Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="comp[]" required placeholder="company Name" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Department Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="dept[]" required placeholder="Department Name" class='cname_990s_EXp'/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
From Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2011" data-initial-month="9" class='TEx_About_allihh' name="exsdate[]" required/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
To Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2012" data-initial-month="10" class='TEx_About_allihh' name="exedate[]" required/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Profile <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="profile[]" required placeholder="Profile" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
</div>
<input type="button" name="addmore" value="Add More" class='button small white' onclick='duplicate();'/>
</div>
</div>
</div></div>
js
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicetor" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
here i want the new fields when added should be empty (right now it is showing the same content with pre filled values in textbox )
second issue is i want to insert the data in table for each value of the array i know this can be donr by foreach loop
PHP
$comps=$_POST['comp'];
$profile=$_POST['profile'];
$exedate=$_POST['exedate'];
$exsdate=$_POST['exsdate'];
$dept=$_POST['dept'];
if(empty($comps) || empty($profile) || empty($exedate) || empty($exsdate) || empty($dept) ){
echo 'Please Fill all the fields marked with *';die;
}
foreach($comps as $value){
// insert into tablename (field1,field2,field3,...) values ('comp1','dep1','profile1'....)
// insert as many feilds as the no of elements in the array
}
please suggest me with this php code how to use the foreach loop so that i can insert as many rows as the no of elements in the array with corrosponging values in another array
pleaes note that this question has two questions written please feel free to help for any of the question.
one is wth php and anothr with ajax
Use following code to clear Cloned form :
NOTE : Must add jquery file in document
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
</script>
Here is code with your new requirement :
To Add remove button if user want to remove form block section user
can easily :
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
addButton(clone.id,i);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
function addButton(id,ii){
var divId = '#'+id;
$(divId).append('<input type="button" value="Remove" class="button small white" id="'+ii+'" onclick="rBlock('+ii+')" />');
}
function rBlock(ii){
$('#'+ii).on('click', function(e){
var parentDiv = $(this).parent();
if(parentDiv.attr('id') !== ii){
parentDiv.remove();
}
});
$('#'+ii).trigger( "click" );
}
</script>