How to append a dropdown list before a button? - javascript

So I have a div that holds a dropdown list of items. I want the user to add more dropdown list's by pressing a button.
I managed this, but the problem I'm facing is that the new list gets appended after the button. I want the button to be always underneath the dropdown list.
I know that there is an option called insertBefore(), but I don't really know how to use it correctly in my case.
Oh and by the way, do you guys have any thoughts about how to give each new dropdown list a unique name? Because it is a form that I am planning on sending later on. I think I need to work with counters in my script file, but I om not sure yet.
So the HTML:
<form role="form" class="contact-form" id="contact-form" method="post">
<div class="form-group">
..not important for the question...
</div>
<div class="form-group">
<div class="controls" id="dropdown_item">
<select class="offerte_product" name="product_1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<input id="add_option" type="submit" value="Add More" onclick="return false" />
</div>
</div>
<div class="form-group">
..not important for the question...
</div>
And the script I am using is:
<script>
$(function(){
$('#add_option').on('click',function(){
var r= $('<select class="offerte_product" name="product_2"> <option value="volvo">Volvo</option> </select> ');
$("#dropdown_item").append(r);
});
});
So do I need to put insertBefore somewhere before the append(r)? I really have no clue.

Just put the button outside the div:
<div class="controls" id="dropdown_item">
<select class="offerte_product" name="product_1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
<input id="add_option" type="submit" value="Add More" onclick="return false" />
You can keep appending to the div and the button will still be below it.

I created fiddle for this question.You can create different name according to product group ID.
$(function(){
var productGroupID=1;
$('#add_option').on('click',function(){
productGroupID+=1;
var r= $('<select class="offerte_product" name=product_'+productGroupID+'> <option value="volvo">Volvo</option> </select> ');
$("#dropdown_item").append(r);
});
});
https://jsfiddle.net/ypaudyal/15jt7tLf/
But If you are posting to the server, I suggest you to use same name and collect the selected values in collection.

Related

Pass the text from a form Select-Option to a text input field

I would like to pass the text portion (not the value) of a form Select-Option to a hidden text-input field within the same form when the user makes a selection.
I have explored some java and PHP 'examples' I found in my research, but none of them seem to work for me.
I have posted a raw example of the form to see if anyone can lead me to water. Any help wouold be appreciated.
HMTL
<html>
<head>
</head>
<body>
<form action="fruitBasket.php" method="post" enctype="multipart/form-data">
<select id="fruitSelector" name="fruitSelector">
<option value="0" selected="selected" disabled="disabled">Select Fruit</option>
<option value="1">Grapes</option>
<option value="2">Strawberries</option>
<option value="3">Peaches</option>
<option value="4">Blueberries</option>
</select>
<br>
<br>
<input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears
here.">
</form>
</body>
</html>
It's not as easy as getting the selected option's value, which can be retrieved simply as selectElement.value, yet it's not difficult at all.
selectElement.options will give you an array of ALL the options inside the select element.
You will find the selected option's index to be selectElement.selectedIndex.
With that said, you can access to the selected option like this: selectElement.options[selectElement.selectedIndex].
Finally, you can get the text property like this: selectElement.options[selectElement.selectedIndex].text
Here's the code:
// THIS CONSTANT REPRESENTS THE <select> ELEMENT
const theSelect = document.getElementById('fruitSelector')
// THIS LINE BINDS THE input EVENT TO THE ABOVE select ELEMENT
// IT WILL BE EXECUTED EVERYTIME THE USER SELECTS AN OPTION
theSelect.addEventListener('input', function() {
// THIS IS HOW YOU GET THE SELECTED OPTION'S TEXT
let selectedOptText = theSelect.options[theSelect.selectedIndex].text
// FINALLY, THIS COPIES THE ABOVE TEXT TO THE INPUT ELEMENT:
document.querySelector('.hiddenField').value = selectedOptText;
})
<form action="fruitBasket.php" method="post" enctype="multipart/form-data">
<select id="fruitSelector" name="fruitSelector">
<option value="0" selected="selected" disabled="disabled">Select Fruit</option>
<option value="1">Grapes</option>
<option value="2">Strawberries</option>
<option value="3">Peaches</option>
<option value="4">Blueberries</option>
</select>
<br>
<br>
<input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears
here.">
</form>
well if you want to pass the text portion you should add the names as the values too like
---
code
---
<option value="Grapes">Grapes</option>
<option value="Strawberries">Strawberries</option>
---
code
---

Check string in select option

I have created with javascript and I get a result of a string.I get that result on my html code
<div id="results"></div>
Next,I want when I select for example Red to check if it is the the same thing (string), the select option - > Red with the string of this code
<div id="results"></div>
I was trying to do it but I failed.It is not working not even sure ,if I press the submit button I will send the string.
<div id="results"></div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="submit" value="results"/>
It appears that you want to check whether the selected option is equal to the text value of the div #results. You can achieve this effect like so:
$(document).ready(function(){
var select = $("select");
$("input[type=\"button\"]").click(function(){
var text = select.find(":selected").text();
if(text==$("#results").text()){
$("#results").html(text+" is equal!");
}else{
$("#results").html(text+" is not equal :(");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="results">Red</div>
<form method="post" >
<select >
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input id="results" type="button" value="results"/>
</form>
A form is going to be Sending data somewhere, it would be best to remove the form, leaving the select and button elements. In the button add the code onclick='myFunction() ; when the button is clicked it will run the javascript function called myFunction(). Also you need to give the select a Id. I'm using selectInput
<script>myFunction() { document.getElementById('result').innerHTML = document.getElementById('selectInput').value;} </script>
Now when ever the button is pressed it will set the content of the div equal to the value entity in the selected select box option
You lack an action attribute.
<form method="post" action="path/to/file">
<select name="select">
<option value="">--Please choose an option--</option>
<option value="R">Red</option>
<option value="B">Black</option>
</select>
<input type="submit" value="Get Results" />
</form>
Use a function, and a regular button. No form is needed.
<button onclick='func()'></button>
const func = () => {...}

setting value of an input with jQuery doesn't work

I'm trying to set the value of a dropdown list based on another dropdown list value inside Angular and using jQuery, it works and it auto selects the wanted value but it doesn't add the value to the database after submitting. I'm sure everything is fine concerning the database connection because choosing any other selected value (for example euro in this case) is added to database.
$(document).ready(function() {
$("#country").change(function() {
var val = $(this).val();
if (val == "usa") {
$("#currency").val("dollar");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form (ngSubmit)="onSubmit()">
<select id="country" name="country">
<option value="usa">usa</option>
<option value="france">france</option>
</select>
<select id="currency" name="currency">
<option value="dollar">dollar</option>
<option value="euro">euro</option>
</select>
<button type="submit" class="btn btn-primary">submit </button>
</form>
NB: Dollar becomes selected but when submitting it's not added to database, whereas if I remove the jQuery function and choose manually the currency , it adds to the database and everything is fine .
The jQuery code seems to be good... but my question is, why are you using jQuery to update a form in Angular.
Did you evaluate use tempalte-driven or reactive forms instead? Below you can find your form written as template driven.
<form (ngSubmit)="onSubmit()">
<select id="country" name="country" (change)="onCountryChange()" [(ngModel)]="selectedCountry">
<option
*ngFor="let country of countries"
[value]="country">
{{ country }}
</option>
</select>
<select id="currency" name="currency" [(ngModel)]="selectedCurrency">
<option
*ngFor="let currency of currencies"
[value]="currency">
{{ currency }}
</option>
</select>
<button type="submit" class="btn btn-primary">submit </button>
</form>
And in this plunkr you can find the full example using template-driven form... but if I where you, I would go for the reactive form approach.

Changing display attribute by dropdown selection

So I'm trying to make an interactive form where the value of one dropdown affects the content of another drop down. I have seen some similar question on SO, and I decided to take the best from all answers. Anyway I'm stuck at the last part and can't seem to figure out why it wont work.
The form:
<div class="form-group">
<label class="col-lg-2 control-label">Dienst</label>
<div class="col-lg-2">
<select id="dienst" name="dienst" class="form-control">
<option value"" disable selected> </option>
<option value="Psychiatrie">Psychiatrie</option>
<option value="Oncologie">Oncologie</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Ziekte</label>
<div class="col-lg-2">
<select name="ziekte" class="form-control">
<option value"" disable selected> </option>
<option class="Psychiatrie_select" value"" >Jong Dementie</option>
<option class="Psychiatrie_select" value"" >Neuropsychiatrische stoornissen</option>
<option class="Oncologie_select" value"" >Other</option>
</select>
</div>
</div>
The JS code
$('select#dienst').on('change', function() {
event.preventDefault();
var dienst = $('[name="dienst"]').val();
if(dienst == "Psychiatrie"){
document.getElementsByClassName(Psychiatrie_select).style.display = 'block';
}
});
The logic behind it:
I first get the value of the first drop down list ( id = dienst ) and based on that I want to change the display value of the options of the second drop down ( where class is Psychiatrie_select )
I have also debugged by console.log(dienst) and that shows that the selection of the first drop down menu is stored in dienst. What could be wrong because my css display attribute doesn't seem to change.

Hiding a class of Div depending on Select statement option

I'm fairly new to javascript and I'm trying to make an form for my website and I'm stuck on the javascript,
This is what I have:
<script type="text/javascript">
function hide(opt) {
if (getElementsByClassName(opt).style.display='none';){
getElementsByClassName(opt).style.display='block';
}
else{
getElementsByClassName(opt).style.display='none';
}
}
</script>
What I intended the script to do was recieve a variable (the option chosen by the user) and then reveal all the elements with the class of the same name (so if the option was orc the orc div would be displayed, but be hidden if the option chosen was elf etc.)
Html:
<form name="chargen" action="" method="post">
Name:<Input name="name" type="text" />
Gender:<select name="gender">
<option>Choose Gender...</option>
<option>Male</option>
<option>Female</option>
</select>
Species:<select name="species" onchange="hide(document.chargen.species.options[
document.chargen.species.selectedIndex ].value)">
<option> Choose Species...</option>
<option value="human">Human</option>
<option value="orc">Orc</option>
<option value="elf">Elf</option>
<option value="dwarf">Dwarf</option>
<option value="drow">Drow</option>
<option value="ent">Ent</option>
</select>
<div class="human" style="display:none;">
Sub Species:<select name="subspecies1">
<option>Norseman</option>
<option>Hellenic</option>
<option>Heartlander</option>
</select>
</div>
<div class="orc" style="display:none;">
Sub Species:<select name="subspecies2">
<option>Black Orc</option>
<option>Fel Orc</option>
<option>Green Orc</option>
</select>
</div>
<div class="human" style="display:none;">
Homeland:<select name="homeland1">
<option>Choose Homeland...</option>
<option value="citadel">Citadel</option>
<option value="wildharn">Wildharn</option>
<option value="Merith">Merith</option>
</select>
</div>
<div class="orc" style="display:none;">
Homeland:<select name="homeland2">
<option>Choose Homeland...</option>
<option value="1">Berherak</option>
<option value="2">Vasberan</option>
</select>
</div>
Unfortunately nothing happens when I change the contents of the species combobox (I've tried on multiple browsers) What am I doing wrong?
I realise that getElementsByClassName() is a HTML5 function, but according to the interwebs it is compatible with all major browsers.
Thanks for your time
getElementsByClassName returns an array, you must iterate on the result. And be careful to the = in tests (instead of ==).
But I suggest you have a look at jquery. Your life will be easier as what you want can be done as :
$('.human, .orc, .elf, .dwarf, .drow, .ent').hide();
$('.'+opt).show();
(see fiddle : http://jsfiddle.net/dystroy/2GmZ3/)

Categories