re-adding HTML into a DIV using JavaScript/JQuery - javascript

Hi All I have the following Div as seen below:
<div id = '1'>
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
when the user clicks on the button, I want to add the following Divs again:
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
Is this possible to achieve with JavaScript or the jQuery onclick function?

You can use clone method with insertAfter:
HTML:
<div id='1'>
<div class="template"> <!-- mark a clone target -->
...
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
JS:
var $template = $('.template');
$('input[type=button]').click(function() {
$template.clone().insertAfter($template);
});
Demo: http://jsfiddle.net/VcBrz/

Try this:
<script>
$(document).ready(function(){
var divID='abc';
var $mainDiv=$('#'+divID);
$mainDiv.find('input[name="addNewRow"]').eq(0).click(function(){
var $this=$(this);
var $div=$(this).parents('div').eq(0).prev('div').clone();
$this.parents('div').eq(0).prev('div').after($div);
});
});
</script>
Demo: http://jsfiddle.net/xT62m/

The best way is to clone that div which you want to add to div#1.
For easier manipulation, please add classes to div with button and to each div which represents row.
HTML:
<div id = 'id1'>
<div class='row'>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div class='buttonHolder'>
<input type="button" name="addNewRow" value="Add Row" />
</div>
</div>
Javascript (with jQuery):
$(document).ready(function(){
$('.buttonHolder input[type=button]').on('click', function(){
//Clone existing row to template.
var row = $('#id1 .row').first().clone();
//Clear template
$('input', row).val('');
$(row).insertBefore('.buttonHolder input[type=button]');
});
});
jsFiddle example: http://jsfiddle.net/9Z2RT/1/

make html like this:
<div id="container">
<div class= 'template'>
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
</div>
</div>
<div>
<input type="button" name="addNewRow" id="btnAddRow" value="Add Row" />
</div>
Click Function:
$('#btnAddRow').click(function(){
var row = $('.template').first().clone();
$('#container').append(row);
});
Here is Fiddle DEMO

The simpliest way will be:
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<script>
var m_TextToAdd = '<div> ';
m_TextToAdd += '<div> ';
m_TextToAdd += ' <label class="right inline">Response:</label>';
m_TextToAdd += '</div>';
m_TextToAdd += '<div>';
m_TextToAdd += ' <input type="text" name="responseText[]" value="" maxlength="400" /> ';
m_TextToAdd += '</div>';
m_TextToAdd += ' <div>';
m_TextToAdd += ' <input type="radio" name="responseRadio[]" value="" />';
m_TextToAdd += ' </div>';
m_TextToAdd += '</div>';
function AddContent() {
document.getElementById('div1').innerHTML += m_TextToAdd;
}
</script>
</head>
<body>
<div id = 'div1'>
<div>
<div>
<label class="right inline">Response:</label>
</div>
<div>
<input type="text" name="responseText[]" value="" maxlength="400" />
</div>
<div>
<input type="radio" name="responseRadio[]" value="" />
</div>
</div>
<div>
<input type="button" name="addNewRow" value="Add Row" onclick='AddContent();'/>
</div>
</div>
</body>
</html>
Anyhow, it heart my eyes to see it :-)
I think the next code is more readable:
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<script type='text/javascript'>
function AddContent() {
var dest = document.getElementById('div1');
//add label
var lbl = document.createElement('label');
lbl.innerHTML = 'Response:';
lbl.className = 'right inline';
dest.appendChild(lbl);
//add line break
dest.appendChild(document.createElement('br'));
//add text input
var input = document.createElement('input');
input.type = 'text';
input.name = 'responseText[]';
input.maxlength="400";
dest.appendChild(input);
//add line break
dest.appendChild(document.createElement('br'));
//add radio button
input = document.createElement('input');
input.type="radio";
input.name="responseRadio[]";
dest.appendChild(input);
//add line break
dest.appendChild(document.createElement('br'));
}
</script>
</head>
<body>
<div id = 'div1'>
<label class="right inline">Response:</label>
<br>
<input class='nextLine' type="text" name="responseText[]" value="" maxlength="400" />
<br>
<input class='nextLine' type="radio" name="responseRadio[]" value="" />
<br>
<input class='nextLine' type="button" name="addNewRow" value="Add Row" onclick='AddContent();'/>
<br>
</body>
</html>

Yes, use the jquery append functionality https://api.jquery.com/append/
$('#1').append(html);
Here is a working jsfiddle http://jsfiddle.net/ZqQAu/1/

Related

Cloning a div tag while also changing id attributes of it elements using JavaScript (Multiple elements )

I am looking to clone a div while also changing id's of the elements inside the mentioned div
The code i am using clone the div is
<!DOCTYPE html>
<html lang="en">
<body>
<form>
<div class="dynamic-field" id="dynamic-field-1">
<div>
<label for="name" class="hidden-md">Name</label>
<input type="text" id="name-1" class="form-control" name="field[]" />
</div>
<div>
<label for="age" class="hidden-md">Age</label>
<input type="text" id="age-1" class="form-control" name="field[]" />
</div>
</div>
<div>
<button type="button" id="add-button">
Add
</button>
</div>
</form>
<script src='https://code.jquery.com/jquery-3.3.1.slim.min.js'></script>
<script>
$(document).ready(function () {
var buttonAdd = $("#add-button");
var className = ".dynamic-field";
var count = 0;
function totalFields() {
return $(className).length;
}
function addNewField() {
count = totalFields() + 1;
field = $("#dynamic-field-1").clone();
field.attr("id", "dynamic-field-" + count);
field.find("input").val("");
$(className + ":last").after($(field));
}
buttonAdd.click(function () {
addNewField();
});
});
</script>
</body>
</html>
The code used can clone div and change its id in an incremental manner. the problem is changing the element input id and name of the label
the cloned div's element's id needs to be like eg field-1,field2,..etc
The expected Result is..
<form>
<div class="dynamic-field" id="dynamic-field-">
<div>
<label for="name" class="hidden-md">Name</label>
<input type="text" id="name-1" class="form-control" name="field[]" />
</div>
<div>
<label for="age" class="hidden-md">Age</label>
<input type="text" id="age-1" class="form-control" name="field[]" />
</div>
</div>
<div class="dynamic-field" id="dynamic-field-2">
<div>
<label for="name" class="hidden-md">Name</label>
<input type="text" id="name-2" class="form-control" name="field[]" />
</div>
<div>
<label for="age" class="hidden-md">Age</label>
<input type="text" id="age-2" class="form-control" name="field[]" />
</div>
</div>
<div>
<button type="button" id="add-button">
Add
</button>
</div>
How can i achieve by altering the existing code and not using an entirely different method
Using Jquery attr:
field.find("input").attr("id","field-" + count);
field.find("label").attr("for","field-" + count);

how to make a picture become interactive with buttons?

*[1]: https://i.stack.imgur.com/WmJv1.jpg
Hi everyone, I would like to thank any help in advance.
I'm quite new to this whole coding world, so i have been given a project to do. I have already set up the HTML file to how I want it to look and etc.... The only problem I'm currently having is, I'm not sure how to use javascript to make the buttons work and store the information. Would anyone share some light on how to get the beds to become interactive? I guess once I can get the beds to be interactive with the buttons I can somewhat play around with the rest and see how I get on.
<!DOCTYPE html>
<html>
<head>
<title> Ward Beds </title>
<style>
body{ border: groove 4px; }
</style>
</head>
<body bgcolor="LIGHTSKYBLUE">
<form
<div
</div>
<p>
</p>
<img id="Bed1" src="bedleftempty.gif" /> <img id="Bed5" src="BedREmpty.gif" />
<div
</div>
<img id="Bed2" src="bedleftempty.gif" /> <img id="Bed6" src="BedREmpty.gif" />
<div
</div>
<img id="Bed3" src="bedleftempty.gif" /> <img id="Bed7" src="BedREmpty.gif" />
<div
</div>
<img id="Bed4" src="bedleftempty.gif" /> <img id="Bed8" src="BedREmpty.gif" />
<div
</div>
<center>
<input id="btnAdmit" type="button" value="Admit"
onclick="btnAdmit_OnClick()" > <input id="btnDischarge" type="button" value="Discharge"
onclick="btnDischarge_OnClick()" />
<div
</div>
<p>
<input id="btnMale" type="button" value="Male"
onclick="btnMale_OnClick()" />
<div
</div>
<input id="btnFemale" type="button" value="Female"
onclick="btnFemale_OnClick()" />
<div
</div>
<input id="btnUnknown" type="button" value="Unknown"
onclick="btnUnknown_OnClick()" />
<div
</div>
</p>
<p>
<label>First Name</label> <input type="text" id="myText" value=" " /> <label>Last Name</label> <input type="text" id="myText" value=" " />
</p>
<label> Location of Surgery</label>
<div
</div>
<input type="checkbox" name="LeftArm" value="LeftLeg"> LeftArm<br> />
<div
</div>
<input type="checkbox" name="RightArm" value="RightLeg" > RightArm<br> />
<div
</div>
<input type="checkbox" name="LeftLeg" value="LeftLeg"> LeftLeg<br> />
<div
</div>
<input type="checkbox" name="RightLeg" value="RightLeg"> RightLeg<br> />
<div
</div>
<input type="checkbox" name="Unknown" value="Unknown"> Unknown<br> />
<div
</div>
<input type="checkbox" name="Head" value="Head"> Head<br> />
<div
</div>
<input type="checkbox" name="Chest" value="Chest"> Chest<br> />
<div
</div>
<input type="checkbox" name="Abdomen" value="Abdomen"> Abdomen<br> />
<div
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
<script language="javascript">
Well my advise advice is to start with simple HTML tutorials.
Because there is a lot of invalid html and some invalid css.
function GetId(id) { return document.getElementById(id) }
// Store information for eatch bed in an array
var beds = [],
// Stores amount of max beds
maxBeds = 8,
// Get beds paragraph
htmlBeds = GetId("beds");
// Loops the amount of maxBeds by increasing i eatch time
for (let i = 0; i < maxBeds; i++) {
// Add an empy bed.
htmlBeds.innerHTML += '<img id="Bed'+(i+1)+'" src="http://mtdef.com/Lib/Img/StackOverflow/bed.png" onclick="bed_Onclick('+i+')"> ';
if (i % 2) htmlBeds.innerHTML += '<br>';
}
//functions you request from the html
function btnAdmit_OnClick() {
let gender, fullName, surgeryLocation = "";
if (GetId('btnMale').checked) gender = "Male";
if (GetId('btnFemale').checked) gender = "Female";
if (GetId('btnUnknown').checked) gender = "Unknown";
fullName = GetId('FirstName').value + " " + GetId('LastName').value;
// Loop 8 times over the Location of Surgery by increasing i eatch time.
for (let i = 0; i < 8; i++) {
let LoS = GetId("LoS"+i);
if (LoS.checked) surgeryLocation += LoS.value + " ";
}
//push patient object to array
beds.push({
gender:gender,
fullName:fullName,
surgeryLocation:surgeryLocation
});
}
//removes last added patient
function btnDischarge_OnClick() {
beds.splice(-1,1);
}
//shows patients stats
function bed_Onclick(bedId) {
if (beds[bedId] === undefined) console.log("bed: " + (bedId+1) +
"\nis empty");
else console.log("bed: " + (bedId+1) +
"\ngender: " + beds[bedId].gender +
"\nfull name: " + beds[bedId].fullName +
"\nlocation of surgery: " + beds[bedId].surgeryLocation
);
}
body {
background-color: lightblue;
border: groove 4px;
}
<center>
<!-- Get filled by JavaScript -->
<p id=beds></p>
<input id="btnAdmit" type="button" value="Admit" onclick="btnAdmit_OnClick()" >
<input id="btnDischarge" type="button" value="Discharge" onclick="btnDischarge_OnClick()" >
<p>
<input id="btnMale" type="radio" name="gender" value="Male">
<label for="btnMale">Male</label><br>
<input id="btnFemale" type="radio" name="gender" value="Female">
<label for="btnFemale">Female</label><br>
<input id="btnUnknown" type="radio" name="gender" value="Unknown" checked="checked">
<label for="btnUnknown">Unknown</label><br>
</p>
<p>
<label>First Name</label>
<input type="text" id="FirstName" value="John"> <br>
<label>Last Name</label>
<input type="text" id="LastName" value="Doe">
</p>
<label> Location of Surgery</label><br>
<input type="checkbox" id="LoS0" value="LeftArm"> LeftArm<br>
<input type="checkbox" id="LoS1" value="RightArm" > RightArm<br>
<input type="checkbox" id="LoS2" value="LeftLeg"> LeftLeg<br>
<input type="checkbox" id="LoS3" value="RightLeg"> RightLeg<br>
<input type="checkbox" id="LoS4" value="Unknown"> Unknown<br>
<input type="checkbox" id="LoS5" value="Head"> Head<br>
<input type="checkbox" id="LoS6" value="Chest"> Chest<br>
<input type="checkbox" id="LoS7" value="Abdomen"> Abdomen<br>
<input type="submit" value="Submit">
</center>
I hope that the comments are enough for you
one problem that might be causing you to not having stuff to work is that, in the example code you gave, you haven`t close the starting div tags and a couple over tags properly.
you have put ... that should help but for the button it seems that you have done it right but in your js file or in the script tag you just put
Female_OnClick() {
what you want it to do
}
try closing all the tags properly, and try that javascript thing aswell and if it still doesnt work tell me and i may be able to help...

How to show up the div on button click which is not actually set to none in html?

Im trying it with laravel. On button click I need to display the same div .
My code:
<h6>Other features </h6>
<div id="add1">
<input type="text" name="selprice" />
<input type="submit" value="+" id="add">
</div>
This is my html code.Here,when I click the button**(ie.,+)** it should show up the same div(ie add1).
Script code:
<script type="text/javascript">
$(document).ready(function () {
$("#add").click(function () {
$("#add1").show();
});
});
</script>
This is what I have tried.
if you are cloning div use class instead of id.
use this context to get the click element
use append to add the cloned div to container
$(document).ready(function() {
$(document).on("click",".add",function() {
$("#container").append($(this).parent(".add1").clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=container>
<div class="add1">
<h6>Other features </h6>
<input type="text" name="selprice" />
<input type="submit" value="+" class="add">
</div>
</div>
Update
$(document).ready(function() {
$(document).on("click", ".add", function() {
var clone = '<div class="add1"><input type="text" name="selprice" /><input type="submit" value="+" class="add"></div>';
$("#container").append(clone);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=container>
<div class="add1">
<h6>Other features </h6>
<input type="text" name="selprice" />
<input type="submit" value="+" class="add">
</div>
</div>
Here you go with the solution https://jsfiddle.net/nuu4ofwu/2/
var cnt = 1;
$(document).on('click', 'input[type=submit]', function(){
cnt++;
var div = $(this).parent().clone();
$('body').append(div);
$('div:last-child').attr('id', 'add' + cnt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="add1">
<h6>Other features </h6>
<input type="text" name="selprice" />
<input type="submit" value="+" id="add" />
</div>
You should define another div as a template:
HTML:
<div id="template" style="display:none;">
<div id="add_2">
<h6>Other features</h6>
<input type="text" name="selprice" />
<input type="submit" value="+" id="add_button_number"></div>
</div>
</div>
Javascript:
<script>
$('#add').click(function(){
var str = $('#add_2').html();
$('#add1').after(str);
})
</script>

Calculator form alternative

I have the current code below, which is working. The problem is this code will be in a form and i can't have nested forms. How do i change the code, so this works with a div parent element instead of a form?
<form>
<script type="text/javascript">
function inmet(form){
form.in2met.value = ((form.inch.value -0) * 25.4).toFixed(2)
}
</script>
<div id="calcbody">
<div class="calctitle">Convert <br />Inches to Millimetres</div>
<div class="singcalcquestion">Enter the Inches:
<input class="box1" type="text" name="inch" />
</div>
<div class="singsubmit">
<input onclick="inmet(this.form)" type="button" value="GO" />
</div>
<div class="singcalcanswer">Equals in Millimetres:<br />
<input class="calcbox2" type="text" readonly="readonly" name="in2met" />
</div>
</div>
</form>
One option would be to use Element.getElementsByClassName() or a similar method to get the input field you want:
<div id="form-root">
<script type="text/javascript">
function inmet(calcRoot){
calcRoot.getElementsByClassName('calcbox2')[0].value = ((form.inch.value -0) * 25.4).toFixed(2);
}
// example: inmet(document.getElementById('form-root'))
</script>
<div id="calcbody">
<div class="calctitle">Convert <br />Inches to Millimetres</div>
<div class="singcalcquestion">Enter the Inches: <input class="box1" type="text" name="inch" /></div>
<div class="singsubmit"><input onclick="inmet(document.getElementById('form-root'))" type="button" value="GO" /></div>
<div class="singcalcanswer">Equals in Millimetres:<br /><input class="calcbox2" type="text" readonly="readonly" name="in2met" /></div>
</div>
</div>
Not the cleanest solution, but it should do the job:
<div>
<script>
function inmet() {
document.getElementById('in2met').value = ((document.getElementById('inch').value - 0) * 25.4).toFixed(2)
}
</script>
<div id="calcbody">
<div class="calctitle">Convert <br/>Inches to Millimetres</div>
<div class="singcalcquestion">
<label for="inch">Enter the Inches:</label>
<input class="box1" type="text" name="inch" id="inch"/>
</div>
<div class="singsubmit">
<input onclick="inmet()" type="button" value="GO"/>
</div>
<div class="singcalcanswer">
<label for="in2met">Equals in Millimetres:</label>
<input class="calcbox2" type="text" readonly="readonly" name="in2met" id="in2met"/>
</div>
</div>
</div>

jQuery how to get div element value from radio button and assign value to a specific div

Here I need to get the selected radio button value (123,456,789) and assign it to valueee div element? I used document.getElementsById, but couldn't get what I need.
Any help would be highly appreciated.
<!DOCTYPE html>
<html>
<head>
<title>Radio Button Selection</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#radio_submit").click(function(e) {
var checked_option_radio = document.getElementsByName("deff").value;
if (checked_option_radio === undefined) {
alert('Please select options!');
} else {
alert("inside else");
$('#valueee').html(checked_option_radio);
}
});
});
</script>
</head>
<body>
<form id="myform">
<div>Choose option:</div>
<div>
<input type="radio" name="user_options" />
</div>
<div name="deff" id="val1">123</div>
<span>CSS</span>
<br></br>
<div>
<input type="radio" name="user_options" />
</div>
<div name="deff" id="val2">456</div>
<span>html</span>
<br></br>
<div>
<input type="radio" name="user_options" />
</div>
<div name="deff" id="val3">678</div>
<span>jquery</span>
<br></br>
<div>
<input type="radio" name="user_options" />
</div>
<div name="deff" id="val4">675</div>
<span>JS</span>
<br></br>
<div><button id="radio_submit" type="button">Show Selected Radio</button></div>
</form>
<div id="valueee"></div>
</body>
</html>
jQuery
$(document).ready(function() {
$("#radio_submit").click(function (e) {
var checked_option_radio = $("input[name=user_options]:checked").val();
});
});
Full Code
$(document).ready(function() {
$("#radio_submit").click(function (e) {
var checked_option_radio = $("input[name=user_options]:checked").val();
if(checked_option_radio===undefined){
alert('Please select options!');
}else{
alert("inside else");
$('#valueee').html(checked_option_radio);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="myform">
<div>Choose option:</div>
<div>
<input type="radio" name="user_options" value="456"/>
</div>
<div name="deff" id="val1" x>123</div>
<span>CSS</span>
<br></br>
<div>
<input type="radio" name="user_options" value="456" />
</div>
<div name="deff" id="val2" >456</div>
<span>html</span>
<br></br>
<div>
<input type="radio" name="user_options" value="678" />
</div>
<div name="deff" id="val3" >678</div>
<span>jquery</span>
<br></br>
<div>
<input type="radio" name="user_options" value="675" />
</div>
<div name="deff" id="val4" >675</div>
<span>JS</span>
<br></br>
<div><button id="radio_submit" type="button">Show Selected Radio</button></div>
</form>
<div id="valueee"></div>
Check jsFiddle
I am adding a class for selected radio button parent div,based on the class I am getting the next div text and printing in the desired place using Jquery.
Rename the name=deff to class=deff.
$("#radio_submit").click(function (e) {
var checked_option_radio = $(this).closest('form').find('div').hasClass('selected');
if(checked_option_radio) {
var hello = $('.selected').next('.deff').text();
$('#valueee').html(hello);
} else {
alert('nothing selected');
var hello2 = "no radio button is selected"
$('#valueee').html(hello2);
}
});
$('input').on('click',function(){
if (!$("input").is(':checked')) {
$(this).parent().addClass('selected').siblings().removeClass('selected');
}
else {
$(this).parent().addClass('selected').siblings().removeClass('selected');
}
});
<form id="myform">
<div>Choose option:</div>
<div>
<input type="radio" name="user_options" />
</div>
<div class="deff" id="val1">123</div>
<span>CSS</span>
<br></br>
<div>
<input type="radio" name="user_options" />
</div>
<div class="deff" id="val2">456</div>
<span>html</span>
<br></br>
<div>
<input type="radio" name="user_options" />
</div>
<div class="deff" id="val3">678</div>
<span>jquery</span>
<br></br>
<div>
<input type="radio" name="user_options" />
</div>
<div class="deff" id="val4">675</div>
<span>JS</span>
<br></br>
<div><button id="radio_submit" type="button">Show Selected Radio</button></div>
</form>
<div id="valueee"></div>
http://jsfiddle.net/silpa/xeb9hoyr/2/
Here is the updated code to get input value
var check_div = $('.selected').next().is('div');
var check_input = $('.selected').next().is('input');
var div_value = $('.selected').next('.deff').text();
var input_value = $('.selected').next('input').val();
if(check_div){
$('#valueee').html(div_value);
}
if(check_input){
$('#valueee').html(input_value);
}
http://jsfiddle.net/silpa/xeb9hoyr/9/
since you have the jquery library implemented use
$('#divid').val(somevalue);

Categories

Resources