I would like to add some functionality with the below code that only 5 times one can click the add button.
Also I would like to add a delete button with every replicated so when clicked, div is deleted and the counter of the 5 times is decreased.
HTML:
<button id="button" onlick="duplicate()">Add another plan</button>
<div id="duplicater">
<p>Choose Your Mobile Plan</p>
<select>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
</div>
JS:
document.getElementById('button').onclick = duplicate;
var i = 0; var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone); }
A JSFiddle can be found here: http://jsfiddle.net/7x4re/
You just have to add an if before your duplicate code:
document.getElementById('button').onclick = duplicate;
var original = document.getElementById('duplicater');
var i = 1;
function duplicate() {
if (i < 6) {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + i++; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
}
1. Example on JSFiddle.
If you want to disable the button when 5 times clicked, below is the code:
document.getElementById('button').onclick = duplicate;
var original = document.getElementById('duplicater');
var i = 1;
var max = 5;
function duplicate() {
if (i < max + 1) {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicater" + i++; // there can only be one element with an ID
original.parentNode.appendChild(clone);
if (i > max) document.getElementById('button').disabled = true;
}
}
2. And an example on JSFiddle.
3. Finally the master solution with add and remove button. But just in a JSFiddle because the code is large...
4. I know it's already a lot but I improved all this, here is the JSFiddle with add and remove button, disable enable function, min max variable and without any i or count varaible, so it's the ultimate master solution ;)
You can add a button to delete the element like this:
<button id="button">Add another plan</button>
<div id="duplicater">
<p>Choose Your Mobile Plan</p>
<select>
<option value="1">Package 1</option>
<option value="2">Package 2</option>
<option value="3">Package 3</option>
<option value="4">Package 4</option>
<option value="5">Package 5</option>
<option value="6">Package 6</option>
</select>
<button class='removebutton'>Delete</button>
</div>
You can enable a function to fire when it's clicked using jquery:
$('body').on('click', ".removebutton", remove);
Finally, the remove handler can remove the clicked element:
function remove() {
if (count > 1) {
if ($(this).parent().attr('id') != 'duplicater') {
$(this).parent().remove();
count--;
} else {
alert("You can't delete the first plan");
}
} else {
alert("You can't delete the first plan");
}
}
http://jsfiddle.net/JVzCt/
I've used a similar approach to the counter as used by ReeCube.
As this uses jquery, you need to include it, either from your local machine or from somewhere else e.g.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
All the js code should be wrapped in the standard jquery ready function:
$(function(){
// Put your js code here.
});
Related
I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P
I have been playing around with codepen.io and came across this particular issue for which I am not able to resolve.
My following pen does not work in codepen but works locally on my machine, I am not sure if I have to do something extra or enable a feature on codepen to make it work.
Any help most appreciated :)
HTML
<span>Background color:</span>
<select id="background">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<span>Width:</span>
<select id="width">
<option value="100px">100px</option>
<option value="200px">200px</option>
<option value="300px">300px</option>
</select>
<span>height:</span>
<select id="height">
<option value="100px">100px</option>
<option value="200px">200px</option>
<option value="300px">300px</option>
</select>
<br/>
<br/>
<div id="content" style="background:red; width:100px; height:100px;"></div>
JS
// array of virtual DOM objects
var arraySelect = document.getElementsByTagName('select');
var content = document.getElementById('content');
// function
function dropdownStyles() {
// apply the value from the select options (when applied) has the style values for content.
var style = this.id;
var value = this.value;
content.style[style] = value;
}
// create a loop to iterate each select option in document add an event listener to each.
for( var i = 0; i < arraySelect.lenght; i++ ){
// with dropdownStyles() the function will get executed so that is why we don't add the brackets
arraySelect[i].addEventListener('change',dropdownStyles);
}
Red box changer - codepen
Here is the working code.
var arraySelect = document.querySelectorAll('select');
var content = document.getElementById('content');
arraySelect.forEach(function(v){
v.addEventListener('change',dropdownStyles);
})
function dropdownStyles() {
var style = this.id;
var value = this.value;
content.style[style] = value;
}
this code will solve your problem.
There is a typo:
it's length not lenght
for( var i = 0; i < arraySelect.lenght; i++ ){
i < arraySelect.lenght
There is lenght ,not length.
I have created a page with two drop-down menus containing various values.
Now I would like to add a "randomize" button. When clicked, this button would select any of the values at random in both fields. (the values are also copied on a box above each menu).
Project idea for drop down menus
So far I've coded the menus and the words display in the boxes above them when the user selects them. But now I'm trying to add a randomise button that would put any of the values in the drop down as selected and of course displayed in the above text box. Ideally, more values in the drop-down menus would be added every once in a while without making the script dysfunctional... and ideally it would all be contained in a HTML file (calling for JQuery or javascript is ok).
I've looked at this but it doesn't apply.
I also looked at this but it's not really a feature that the user activates.
Very grateful if anyone can help! Thanks
hope this helps
HTML :
<select id="s1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="s2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Javascript:
var minNumber = 0;
var maxNumber = 3;
function randomNumberFromRange(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
I create this fiddle for you...
https://jsfiddle.net/s59g8vdp/
The first example you have provided is very close to what you want to do. You just need to:
Get a random value between 0 and options.length - 1.
Get option[random] and set its selected property to true.
Copy that option's .innerHTML or .value to the .innerHTML or .value of the label on top of the dropdowns.
This is all you probably need:
function randomizeSelect(selectId, fieldId) {
var options = document.getElementById(selectId).children;
var random = Math.floor(options.length * (Math.random() % 1));
var option = options[random];
option.selected = true;
document.getElementById(fieldId).value = option.innerHTML; // You can use .value instead in both places
}
var values = {};
window.onload = function(e) {
document.onchange = function(e) { // Event Delegation: http://davidwalsh.name/event-delegate
var t = e.target;
if(t.tagName == "SELECT")
document.getElementById(t.id.replace("Select","Label")).value = t.children[t.selectedIndex].innerHTML;
}
document.oninput = function(e) {
var t = e.target;
if(t.tagName == "INPUT") {
if(values.hasOwnProperty(t.id))
var options = values[t.id];
else
var options = document.getElementById(t.id.replace("Label","Select")).children;
var currentValue = t.value;
for(i in options) {
if(options[i].innerHTML == currentValue) { // Can also use .value
options[i].selected = true;
break;
}
}
}
}
document.getElementById("randomize").onclick = function(e) {
randomizeSelect("leftSelect", "leftLabel");
randomizeSelect("rightSelect", "rightLabel");
}
}
<input type="text" id="leftLabel" value="Left 1">
<select id="leftSelect">
<option value="l1" selected>Left 1</option>
<option value="l2">Left 2</option>
<option value="l3">Left 3</option>
</select>
<input type="text" id="rightLabel" value="Right 1">
<select id="rightSelect">
<option value="r1" selected>Right 1</option>
<option value="r2">Right 2</option>
<option value="r3">Right 3</option>
</select>
<button id="randomize">RANDOMIZE</button>
This will create random number and click on random div menu:
$(function(){
$(".menu").click(function(){
alert("you clicked "+$(this).text());
});
});
function doSomthing(){
var rand=Math.floor((Math.random() * 5));
alert(rand+1);
var ele = $(".menu").get(rand);
$(ele).click();
}
fiddle example: link
Or you can use this example to put value in the menu, or wherever you want: link 2
just a concept how to make that
$('input').on('click',function(){
var randomnum = Math.floor(Math.random()*$('ul li').length);
alert($('ul li').eq(randomnum).text());
});
DEMO FIDDLE
Randomize Button added
see... ;) i hope this solve your problem!
https://jsfiddle.net/s59g8vdp/1/
Html :
<select id="s1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select id="s2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<a id="randomize" href="#">randomize</a>
Javascript :
var minNumber = 0;
var maxNumber = 3;
$("#randomize").click(function(){
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
});
function randomNumberFromRange(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
$("#s2")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
$("#s1")[0].selectedIndex = randomNumberFromRange(minNumber, maxNumber);
I have a select with loads of options. (Code below shortened for sake of example).
I want it to set the value of the input textfield "hoh" to "10" when you click/select all dropdown options, except one, that should set it to 50.
I imagined something like this would work, but its not. What am I doing wrong here?
<select>
<option onselect="document.getElementById('hoh').value = '50'">Hey</option>
<option onselect="document.getElementById('hoh').value = '10'">Ho</option>
<option onselect="document.getElementById('hoh').value = '10'">Lo</option>
....
</select>
<input type="text" id="hoh" value="10">
Something like this should work:
<script>
function myFunc(val) {
if (val == '50') {
document.getElementById('hoh').value = val;
} else {
document.getElementById('hoh').value = '10';
}
}
</script>
<select onchange="myFunc(this.value)">
<option value="1">one</option>
<option value="2">two</option>
<option value="50">fifty</option>
</select>
http://jsfiddle.net/isherwood/LH57d/3
The onselect event refers to selecting (or highlighting) text. To trigger an action when a dropbox selection changes, use the onchange event trigger for the <select> element.
E.g. Since you didn't already set the value attribute of your option tags.
<select id="myselect" onchange="myFunction()">
<option value="50">Hey</option>
<option value="10">Ho</option>
<option value="10">Lo</option>
....
</select>
and somewhere inside of a <script> tag (presumably in your HTML header) you define your javascript function.
<script type="text/javascript>
function myFunction() {
var dropbox = document.getElementById('myselect');
document.getElementById('hoh').value = dropbox[dropbox.selectedIndex].value;
}
</script>
I'm not sure it's wise to repeat the same value among different options in a droplist, but you could expand on this to implement the result other ways, such as if the sole option which will have value 50 is in a certain position, you could compare the selectedIndex to that position.
you could add an onchange event trigger to the select, and use the value of an option to show in the textbox
see http://jsfiddle.net/Icepickle/5g5pg/ here
<select onchange="setValue(this, 'hoh')">
<option>-- select --</option>
<option value="10">Test</option>
<option value="50">Test 2</option>
</select>
<input type="text" id="hoh" />
with function setValue as
function setValue(source, target) {
var tg = document.getElementById(target);
if (!tg) {
alert('No target element found');
return;
}
if (source.selectedIndex <= 0) {
tg.value = '';
return;
}
var opt = source.options[source.selectedIndex];
tg.value = opt.value;
}
Try this code
var inp = document.getElementById('hoh');
sel.onchange = function(){
var v = this.value;
if( v !== '50'){
v = '10';
}
inp.value = v;
};
Given the following menu http://jsfiddle.net/pYJPc/ using Javascript, how would I iterate through all options and remove them one by one? then re-add them all. I don't want the select menu itself to be removed at all
Here is one way to do it using Vanilla JavaScript JSFiddle Demo:
Here is the markup HTML:
<select id="myselect">
<option value='none'>--Select a page--</option>
<option value="1">W3Schools</option>
<option value="2">Microsoft</option>
<option value="3">AltaVista</option>
</select>
<br/><br/>
<button value='add' id='addbtn' name='addbtn'>add</button>
<button value='delete' id='deletebtn' name='deletebtn'>delete</button>
Using cloneNode to backup your default select options. The addOption will add the backup back to your select if there is no options and the deleteOption will delete all options in your select tag:
//clone our options to a backup
var myselect = document.getElementById('myselect');
var backup = myselect.cloneNode(true).getElementsByTagName('option');
//add backup back into select
function addOption() {
if (myselect.options.length == 0) {
for (var i = 0; i < backup.length; i++) {
myselect.options.add(backup[i].cloneNode(true));
}
}
}
//delete all option in select
function deleteOption() {
while (myselect.options.length != 0) {
myselect.options.remove(myselect.options.length - 1);
}
}
//attach click event to btns
document.getElementById('addbtn').onclick = addOption;
document.getElementById('deletebtn').onclick = deleteOption;
Turns out in IE cloneNode does not really clone it. So, we'll have to create our own cloneNode, and change the backup to:
var backup = IEcloneNode(myselect).getElementsByTagName('option');
//FOR IE
//Reference http://brooknovak.wordpress.com/2009/08/23/ies-clonenode-doesnt-actually-clone/
function IEcloneNode(node) {
// If the node is a text node, then re-create it rather than clone it
var clone = node.nodeType == 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
// Recurse
var child = node.firstChild;
while(child) {
clone.appendChild(IEcloneNode(child));
child = child.nextSibling;
}
return clone;
}
Your HTML :
<select id="menu" onchange="go()">
<option>--Select a page--</option>
<option value="1">W3Schools</option>
<option value="2">Microsoft</option>
<option value="3">AltaVista</option>
</select>
<input id="remove" type="button" value="remove one" >
<input id="repop" type="button" value="repop">
And your JS with jQuery
var buffer=new Array();
$("#remove").click(function() {
buffer.push($("option:first").get(0));
$("option:first").remove();
});
$("#repop").click(function() {
$("select").append(buffer);
});
With jQuery loaded:
var options = $('#menu').children();
children.remove();
$('#menu').insert(children);
Similarly in different libraries as well.
Without a library, you need a little bit more work :)