I want to create multiple DOM elements using javascript. The sequence is 'dropdown', '3 textboxes'. When I click on (+) button it all should be placed together. Will someone help me out this???
<script type="text/javascript">
function add_elements(new1)
{
var i=1;
var sel=document.createElement('new1');
var sel1=document.createElement('new1');
sel.innerHTML='<select><option value="">--SELECT SIZE--</option><option value="6">6</option><option value="8">8</option><option value="10">10</option><option value="12">12</option><option value="14">14</option><option value="16">16</option></select>';
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", 'text');
element.setAttribute("name", 'txtRate');
var foo = document.getElementById("el");
foo.appendChild(element);
}
</script>
Since you tagged the question to jquery,I'm posting this answer
$("#add").click(function () {
var select = $("<select/>");
select.append($("<option/>", {
text: "one",
value: "1"
}));
select.append($("<option/>", {
text: "two",
value: "2"
}));
$("#container").append(select);
$("#container").append($("<input/>", {
type: "text"
}));
$("#container").append($("<input/>", {
type: "text"
}));
$("#container").append($("<input/>", {
type: "text"
}));
});
html
<div id="container"></div>
<input id="add" type="button" value="addElements"/>
you can give any attributes to each element while appending
Demo
Related
I have an array of objects that I'd like to use to populate a Select option dropdown, but these elements do not already exist and must be created from scratch.
I have working code using the createElement method, but I can't use that method nor can I use options.add(new Option()). How else can I create the select and option elements in the JavaScript?
var optionsList = [
{
label: "Option 1",
value: "option-1"
},
{
label: "Option 2",
value: "option-2"
},
{
label: "Option 3",
value: "option-3"
}
];
if (optionsList.length == 0) {
console.log("No data");
} else {
var selectTag = document.createElement("SELECT");
document.body.appendChild(selectTag);
for (var i = 0; i < optionsList.length; i++) {
var option = optionsList[i];
selectTag.options.add(new Option(option.label, option.value));
}
}
You can just make a string with template literals (easier and more concise than concatenation) and append that to the select element:
optionsList.forEach(e => selectTag.innerHTML += `<option value=${e.value}>${e.text}</option>`);
Instead of saying
selectTag.options.add(new Option(...))
Simply create a new 'option' element and then add it to the select tag like this
optionsList.forEach(function(item, index, array) {
var opt = document.createElement("option");
opt.text = item.label;
opt.value = item.value;
selectTag.add(opt);
});
You can look at this link https://www.w3schools.com/jsref/met_select_add.asp for more info.
and a working example here https://jsfiddle.net/L5342j0y/
The following HTML and JavaScript shows how to add a Select and Options using data from an array of objects containing option labels and their values:
<html>
<head>
<meta charset="utf-8">
<script src="app.js"></script>
</head>
<body onload="app()">
<p>Select your choice:</p>
<div id="div-id">
<!-- The select with data gets added here -->
</div>
</body>
</html>
app.js:
function app() {
var optionsList = [
{
label: "Option 1",
value: "option-1"
},
{
label: "Option 2",
value: "option-2"
},
{
label: "Option 3",
value: "option-3"
}
];
var selectTag = document.createElement("select");
for (let optObj of optionsList) {
let optEle = document.createElement("option");
optEle.text = optObj.label;
optEle.value = optObj.value;
selectTag.add(optEle);
}
var div = document.getElementById("div-id");
div.appendChild(selectTag);
};
I'm trying to get the value of the dynamically generated radio button when this button is selected.
Here is my code snippet:
<div id="divContainer">
</div>
Jquery:
$("#divContainer").on("change", $('input[name="name1"]:checked'), function () {
var selectedVal=$('input[name="name1"]:checked').val();
console.log(selectedVal);
});
The value of the selectedVal is returning null here.
Resolution:
The default value was not properly assigned. I updated my code snippet which generates the radio button:
('#radiBtn').attr("value",val);
This resolved the issue.
Remove the $ wrapping from selector just use 'input[name="name1"]:checked't
for getting changed object use this
var div = $("#divContainer").on("change", 'input[name="name1"]:checked', function() {
var selectedVal = $(this).val();
console.log(selectedVal);
});
$('<input>', {
name: 'name1',
type: 'radio',
value: 1
}).appendTo(div);
$('<input>', {
name: 'name1',
type: 'radio',
value: 2
}).appendTo(div);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="divContainer">
</div>
Hi I'm trying to add "children" list items to "family" lists. I have a first form to create the families and a second form which is a select box to create the children and add them to a selected family from the select box. The Ol's ids are dynamically created and the drop down's options dynamically created.
When an option is created, the values are incremented every time a family and option is made.
My plan is to reference the OL families by using the options, basically corresponding to the family by the time it is created.
For example when I make a family1, there will be an option created with that family1 with a value 1, and when family2 is created, an option 2 is created with a value of 2.
I'm trying to append children to the family but I have no idea how to reference the OL's ids
this is what I have so far
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
var i = 1;
$(document).on('click', "#submit", function () {
var str = ' '
var family = document.getElementById('famname').value;
$('#family input[type = text],input[type = text],input[type = text],input[type = text]').each(function () {
str = str + $(this).val() + ' ';
$(this).val('');
});
$("<ol>", {
text: str,
id: "family+" + i
}).appendTo("#container").append($('<button />', {
'class': 'btn2',
text: 'Remove'
}));
$('#select').append($('<option />', {
text: family,
value: i
}));
i++;
});
// Append items functions
$(document).on('click', "#submit2", function () {
var child = prompt("Please enter the child you want to add");
var e = document.getElementById("select");
var str = e.options[e.selectedIndex].value;
$('<li>', {
text: child
}).appendTo( ? ? ? ).append($('<button />', {
'class': 'btn',
text: 'Remove'
}))
});
//delete items functions
$(document).on('click', '.btn', function () {
$(this).closest('li').remove();
});
// delete the list
$(document).on('click', '.btn2', function () {
$(this).parent().next().remove();
$(this).closest('ol').remove();
});
});
</script>
</head>
<body>
<form id ="family" method = "post" target="_parent">
Enter Family Name <input type = "text" name = "famname" id = "famname" > <br>
Enter Address <input type = "text" name = "address"> <br>
Enter Father's name <input type = "text" name = "dad"> <br>
Enter Mother's name<input type = "text" name = "mom"> <br>
<input id="submit" type="button" value="Submit" name="submit">
</form>
<p>Select Which family you want to add a child to</p>
<form id = "child">
<select id ="select">
</select>
<input id="submit2" type="button" value="Submit" name="submit">
</form>
<div id = "container">
</div>
</body>
</html>
Tip and help are appreciated
http://jsfiddle.net/Jnewguy/4LVTz/
Try
$(document).ready(function () {
var i = 1;
var $famname = $('#famname');
var $finputs = $('#family input[type = text]').not('#famname');
$(document).on('click', "#submit", function () {
var family = $famname.val();
var $ol = $("<ol>", {
id: "family-" + i
}).appendTo("#container");
$('<li />', {
text: family
}).append($('<button />', {
'class': 'btn2',
text: 'Remove'
})).appendTo($ol);
$finputs.each(function () {
$('<li />', {
text: this.value
}).appendTo($ol);
$(this).val('');
});
$('#select').append($('<option />', {
text: family,
value: i
}));
i++;
});
// Append items functions
var $select = $('#select')
$(document).on('click', "#submit2", function () {
var child = prompt("Please enter the child you want to add");
$('<li>', {
text: child
}).appendTo('#family-' + $select.val()).append($('<button />', {
'class': 'btn',
text: 'Remove'
}))
});
//delete items functions
$(document).on('click', '.btn', function () {
$(this).closest('li').remove();
});
// delete the list
$(document).on('click', '.btn2', function () {
$(this).parent().next().remove();
$(this).closest('ol').remove();
});
});
Demo: Fiddle
This is the javascript -
<script src='//www.google.com/jsapi' type='text/javascript'></script>
<script type='text/javascript'>
google.load('search', '1', {language: 'en', style: google.loader.themes.BUBBLEGUM});
google.setOnLoadCallback(function() {
var customSearchOptions = {};
var orderByOptions = {};
orderByOptions['keys'] = [{label: 'Relevance', key: ''} , {label: 'Date', key: 'date'}];
customSearchOptions['enableOrderBy'] = true;
customSearchOptions['orderByOptions'] = orderByOptions;
var customSearchControl = new google.search.CustomSearchControl('001216773833632189276:ki_enp2eefa', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
customSearchControl.draw('cse', options);
}, true);
</script>
And its returning input code is with table column-
<td class="gsc-search-button">
<input type="button" value="Search" class="gsc-search-button" title="search">
</td>
Here i want to set the value GO. How can i get it ?
if you only have 1 element in your page follow this:
var searchField = document.getElementsByClassName("gsc-search-button")[0];
searchField.value = "GO";
Example : http://jsfiddle.net/uN2NV/
for multiple elements Try this:
var searchField = document.getElementsByClassName("gsc-search-button");
for(var i =0; i<searchField.length;i++)
{
searchField[i].value = "GO";
}
Example: http://jsfiddle.net/uN2NV/1/
For distinct element among multiple elements that share the same class:
var searchField = document.getElementById("distinct");
searchField.value = "GO";
Example: http://jsfiddle.net/uN2NV/2/
document.querySelector(".gsc-search-button").value = "GO";
if you want just that element, give it an ID
then search for it
var btn = document.getElementById("searchButton");
btn.value = "GO";
If you know that this will be the only item on the page with this class, or want to select all elements with the gsc-search-button class, then one of the other answers will work without modifying the markup.
I'm trying to write a jQuery code that works in this way:
When the page is loaded, it is presents only one field.
Selecting an option from that field, a new field is opened and the option have to be all the option of the first , except the option selected. And so on, also for the other created.
The jsfiddle is shown here
var globalObj = {};
var selectedObj = {};
var unselectedObj = {};
var currentSelection = "";
function deleteByVal(obj,val) {
for (var key in obj) {
if (obj[key] == val) delete obj[key];
}
}
$(document).ready(function () {
$(document).on('click', 'target', function(){
var curSelected = $(this).find(":selected").text();
});
$("#select1").one('click',function(){
$(this).children().each(function () {
globalObj[this.value] = this.innerHTML;
});
unselectedObj = globalObj;
});
$(document).on('change', '.prova > .target', function () {
$('div').removeClass('prova');
var $mySelect = $('<select>', {
class: 'target'
});
var selectedValue = $(this).find(":selected").text();
var found = 0;
$.each(selectedObj, function (val, text) {
if (val === selectedValue) {
found++;
}
});
if (found===0) {
selectedObj[this.value] = selectedValue;
deleteByVal(unselectedObj,selectedValue);
}
console.log(selectedValue);
console.log(selectedObj);
console.log(unselectedObj);
var obj = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML!=selectedValue) {
//code
obj[this.value] = this.innerHTML;
}
});
console.log("Questo rappresenta obj:");
console.log(obj);
console.log("stampa obj conclusa");
$( "select" ).not(this).each(function( index ) {
var temp = {}; //create an object
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
$this = $(this);
console.log("stampa temp");
console.log(temp);
console.log("fine stampa temp");
});
$.each(unselectedObj, function (val, text) {
$mySelect.append($('<option />', {
value: val,
text: text
}));
});
var $input = $('<input>', {
type: 'number',
style: 'width: 35px',
min: '1',
max: '99',
value: '1'
});
var $button = $('<button>', {
type: 'button',
class: 'remove_item',
text: 'delete'
});
$(this).parent().after($('<br>', {
class: 'acapo'
}), $('<div>', {
class: 'prova'
}).append($mySelect, $input, $button));
$(this).unbind('change');
$(this).unbind('click');
$(this).on('click', function(){
currentSelection = $(this).find(":selected").text();
});
$(this).on('change',function(){
console.log("nuovo bind");
var selectedValue = $(this).find(":selected").text();
if (currentSelection !== selectedValue) {
console.log(currentSelection + " to "+ selectedValue);
$( "select" ).not(this).each(function( index ) {
$(this).append($('<option />', {
value: currentSelection,
text: currentSelection
}));
$(this).children().each(function () {
if (this.innerHTML === selectedValue) {
console.log("eliminazione");
$(this).remove();
}
});
});
}
});
});
});
The code has some problems and I was thinking to use an existing plugin instead of that code. Is there anyone that knows a plug-in which makes that work?
Here's an option using javascript templating. I'm declaring my available options at the top in an array, thus separating my data model from the UI. I'm using the handlebars library to then compile a template and append it into the DOM. Fiddle: http://jsfiddle.net/LNP8d/1/
HTML/Handlebars
<script id="select-template" type="text/x-handlebars-template">
<div>
<select class="target" id ="select-{{id}}">
<option value="">Select an option…</option>
{{#each options}}
{{#unless selected}}
<option data-option-key="{{#key}}" value="{{value}}">{{label}}</option>
{{/unless}}
{{/each}}
</select>
<input type="number" style="width: 35px" min="1" max="99" value="1">
</div>
</script>
<div id="container">
</div>
Javascript
//Declare the available options
var options = {
option1: {
value: 1,
label: "Option 1"
},
option2: {
value: 2,
label: "Option 2"
},
option3: {
value: 3,
label: "Option 3"
},
option4: {
value: 4,
label: "Option 4"
},
}
source = $("#select-template").html(),
template = Handlebars.compile(source),
onScreen = 0;
//Adds another select menu
var showSelect = function(){
onScreen++;
$("#container").append(template({id:onScreen, options:options}))
};
//Listens to change events
$("body").on("change", ".target", function(){
options[$(this).find(":selected").data("option-key")].selected = true;
showSelect();
});
//Initialises the UI
showSelect();
Please note: this is not a complete example. If you decide to use this method, you'll need to add some checks for what happens when the options run out and if someone changes an option. I hope it's successful in showing you an alternative a potentially more flexible method though.
I think you are looking for something like this:
http://codeassembly.com/Simple-chained-combobox-plugin-for-jQuery/