I would like to start by saying I am very new to jquery and javascript I rarely use it, however I now find myself in a position where I need to make use of it.
What I am trying to do
I am trying to let admin-user upload matches to db for a round in a competition, thus building the schedule for round X....hope that makes sense
What should happen
if user selects, as an example, 4 from the dropdown box 8 input fields should be created, thus allowing user to enter the 2 teams which will play in each round in each match.
I have tried to code this, (please dont laugh) but the logic and code is completely wrong, if anyone can be so kind to assist me with this problem it would be much appreciated, possibly allowing me to build from this in the future.
JFiddle
https://jsfiddle.net/leela89/zvss0f8L/#&togetherjs=RApSQ2E6Sr
Code
<select id="nrGames" name="nrGame">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<script type="text/javascript">
//create input element for nr games
$("#nrGames").change(function(){
var value = $(this).val;
var nr = 0;
while(nr < value){
$('#games').add('input');
nr++;
}
})
</script>
<!--APPEND INOUT TEXT -->
<div id="games">
</div>
Try to .append() the new elements into the target element,
$("#nrGames").change(function() {
var value = +$(this).val();
value *= 2;
var nr = 0;
var elem = $('#games').empty();
while (nr < value) {
elem.append($('<input>',{name : "whateverNameYouWant"}));
nr++;
}
});
Also .val() is a function not a property.
DEMO
Small update: Different elements for player in each team will be helpful
$("#nrGames").change(function() {
var value = +$(this).val();
var nr = 0;
var elem = $('#games').empty();
while (nr < value) {
elem.append($('<input>',{name : "Team1Player"+nr}));
elem.append($('<input>',{name : "Team2Player"+nr}));
nr++;
}
});
Related
function updateItems() {
const data = {
ItemNames: []
};
var ItemCount = document.getElementById("selectQty").value;
for (var i = 1; i <= ItemCount; i++){
data.ItemLists.push({
id: `ItemName${i}`,
value: document.getElementById(`ItemName${i}`).value
});
}
}
Above is my code, I am trying to create new input text called id="ItemName" to create based on the value in the select combobox called id="selectQty". I created this loop but it doesn't create new input text based on the selected number in the combo box. I am beginner at Javascript and doing exercises. I tried looking for other solution but I can't seem to find any. Any help will be appreciated.
This function will be called on using the select:
<select id="selectQty" onchange="updateItems()">
<option value="0" disabled selected value>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="2">3</option>
<option value="2">4</option>
<option value="2">5</option>
<option value="2">6</option>
<option value="2">7</option>
</select>
This is my input text
<input type="text" id="ItemName" placeholder="Item Name">
You need to use createElement method to create new dynamically added inputs.
To get the value of actual input we need to create we can use _this.value which will be coming from our onclick function.
You might notice this + sign which mean we are converting the string number to actual integer format for looping purposes.
Also, i have also addedlabel to each of your input when they are created you can name the label to what suits you the best.
In addition, to make it look nicer we can add line break <br> to make sure our labels and input are generated in each line.
Lastly, you need to use innerHTML to make sure that you set the results to empty each time you select a different option from the select.
You can also refer to each comment as well i have added in each line of JS code below.
Live Demo:
function updateItems(_this) {
var ItemCount = +_this.value //get the value
var results = document.querySelector('#results') //append results
results.innerHTML = '' //clear the results on each update
for (var i = 1; i <= ItemCount; i++) {
var input = document.createElement('input') //create input
var label = document.createElement("label"); //create label
label.innerText = 'Input ' + i
input.type = "text";
input.placeholder = "Type text here"; //add a placeholder
input.className = "my-inputs"; // set the CSS class
results.appendChild(label); //append label
results.appendChild(document.createElement("br"));
results.appendChild(input); //append input
results.appendChild(document.createElement("br"));
}
}
<select id="membership-members" onchange="updateItems(this)">
<option value="0" disabled selected>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<br>
<br>
<div id="results"></div>
I'd like to add a data value to an option tag in a select element. For example data-price but my problem is that I have multiple select tags. So how do I get JavaScript to grab the data value of that option that the user selects?
How I want it to work:
Select element #1 contains:
<select onchange="updatePrice()">
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
Select element #2 contains:
<select onchange="updatePrice()">
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
Then I'm honestly not sure what to do in the JS... But I want it to grab what the user selected, get the data-price then calculate the total (just by adding select1 + select2).
EDIT: My answer is different than this question because my question is more specific and requires different methods. Even though this is specific it could help a developer in the future by the answers it gets. Therefore it is not a duplicate but a more specific question than the other. Though that question has a simpler answer that could be plugged in if the developer knows how to.
Here is some code matching your discription. A few notes: Use the value attribute to get direct access to the option value from the select element. The unary operator (+) converts the two values from strings to a operatable numbers. The third div is just to show the output total value.
function updatePrice(){
var s1 = document.getElementById("option1");
var s2 = document.getElementById("option2");
var total = +s1.value + +s2.value;
document.getElementById("price").innerHTML = "Total: $" + total
// to get the text within the selected option
var h1 = s1.options[s1.selectedIndex].text;
return total;
}
<select id="option1" onchange="updatePrice()">
<option value="1">Apple $1</option>
<option value="2">Potato $2</option>
<option value="3">Bag of Grapes $3</option>
</select>
<select id="option2" onchange="updatePrice()">
<option value="5">Really good cake</option>
<option value="15">Super Good Cake</option>
</select>
<div id="price"></div>
Let me know if you need any further explanation. Cheers.
This is a bit tricky. You need to give an identifier so our code won't get confused.
<select id="goods1" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
<select id="goods2" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
First, add a global variable to storing current price. Second, store the identifier and the price value. Finally, manipulate the current price.
<script>
let price = 0;
let stored = {};
const updatePrice = elm => {
const id = elm.id;
const selectedPrice = parseInt(
Array.from(
elm.children
).filter(x => x.selected)[0].dataset.price
);
price = 0;
stored[id] = selectedPrice;
Object.keys(stored).forEach(key => price += stored[key]);
console.log(`Price: ${price}`);
};
</script>
Add some unique class to all selectbox whos valued need to be involved in total calculation like mul_ck
//when even a single selectbox change it will trigger re-calculation
$('.mul_ck').change(function(){
var total = 0;
//grab all _mul_ck_ and loop over them
$('.mul_ck').each(function(){
var selectValue = $(this).find(":selected").attr('data-price');
total += parseFloat(selectValue);
});
alert(total);
});
Good Day everyone,
Currently working on an application, inside the settings I have a list of drop down list that my clients can select. Those drop down list are to create an order in which they want those options to appear.
How can you make it, that they cannot select 2 times the same number, and if they do the "new" selection will go replace the "same number" with the old selection.
<select name="temporary-1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="temporary-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="temporary-3">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
I am currently using jQuery in my application, so what I was thinking is to compare each Drop Down on change, and if the same number exist already I would just switch both numbers.
Would it be a proper way? Or is there ways already to do this?
You might want to use the selectize.js library to implement your drop downs, it's located here: https://brianreavis.github.io/selectize.js/
Here's a solution that replaces the options with only ones that haven't been chosen in the other elements
var $selects = $('select.temp'),// added a common class to the elements
opts = $selects.first().html()
$selects.change(function(){
$selects.each(function(){
var otherValues = $selects.not(this).map(function(){
return this.value ? this.value : null;
}).get();
var currVal = this.value;
$(this).html(function(){
return $(opts).filter(function(){
return $.inArray(this.value, otherValues) === -1;
});
}).val(currVal);
});
});
Also requires having an option with no value in each
DEMO
I'm using a similar idea to charlietfl's solution, but I went a little bit of a different route . . . my code disables any options that have already been selected in a different dropdown. Like his, mine also requires that you have an option with no value (there are ways to avoid that, if needed, but, if you can add in a default like that, it makes the code much more simple).
HTML
<select name="temporary-1">
<option value="">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="temporary-2">
<option value="">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="temporary-3">
<option value="">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
JS/jQuery
$("document").ready(function() {
$("select").on("change", disableOptions);
});
function disableOptions() {
var $allSelectInputs = $("select");
var sChangedSelectName = $(this).attr("name");
var $changedSelectOptions = $(this).find("option");
var sChangedSelectVal = $changedSelectOptions.filter(":selected").val();
for (i = 0; i < $changedSelectOptions.length; i++) {
if (!($($changedSelectOptions[i]).prop("disabled"))) {
for (j = 0; j < $allSelectInputs.length; j++) {
if ($($allSelectInputs[j]).attr("name") !== sChangedSelectName) {
var $currentSelectOption = $($($allSelectInputs[j]).find("option")[i]);
if (sChangedSelectVal !== "") {
if ($currentSelectOption.val() === sChangedSelectVal) {
$currentSelectOption.prop("disabled", true);
}
else {
$currentSelectOption.prop("disabled", false);
}
}
}
}
}
}
}
When an option is selected in one of the dropdowns, it will go through the other two and disable the value that matches the selection. By disabling them, instead of removing them, you can easily "reinstate" the optoins, if a new selection is made.
Ideally, you would be able to hide the options, instead of disabling them, but there are browser support issues when it comes to applying display: none; to <option> tags (glares at IE).
Thanks for your answers,
But those were not what I was looking for.
Here is how I did it:
First of, I already had a hidden field used for another purpose (which I forget to mention here).
$('.select_class').change(function () {
var $currentselect = $(this);
var $currentorder = $('input[name=' + $(this).attr('name') + '_current' + ']');
$("select[name^='select_order_']").each(function () {
var $checkcurrent = $('input[name=' + $(this).attr('name') + '_current' + ']');
if (!$(this).is(':disabled')) {
if($(this).prop('name') != $currentselect.prop('name')){
if($(this).val() == $currentselect.val()){
$(this).val($currentorder.val())
$checkcurrent.val($currentorder.val())
}
}
}
});
$currentorder.val($(this).val())
});
The $currentselect takes the field that was modified and keeps it as a variable to be used in the below sections
The $currentorder take the name of the .class_select and add _current (which becomes the hidden field with the current data.
For all the "select_order" I do the following checks:
Create the checkcurrent variable to modify it later if it is needed
Is it disabled, If it is just skip it
does the $currentselect value has the same value has the "select_order"
If it has the same value, change the current "select_order" with the $currentorder value and then allow the change to the $currentselect
change checkcurrent with the new value so the _current has the proper number for each
I am trying to write a JavaScript function where if value 1 from the first dropdown(pcount) automatically selects value 1 for drop down 2(listedname), But then if anything besides value 1 (2,3,4) is chosen I do not want drop down 2 to do anything except default back to please select if value 1 was selected and then changed to another value. I am very new to JavaScript and programming in general and have not been able to find any examples similar to this. So any help will help!
JavaScript Funtion:
<script type="text/javascript">
function leaveChange() {
if (document.getElementById("pcount").value = 1){
document.getElementById("listedname").value = 1;
}else
document.getElementById("listedname").value = 2;
}
}
</script>
Dropdown 1 and 2:
<select id="pcount" onchange="leaveChange()">
<option value="" selected="selected">Please Select</option>
<option value="1">0</option>
<option value="2">1</option>
<option value="3">2</option>
<option value="4">3</option>
</select>
<select id="listedname">
<option value="" selected="selected">Please Select</option>
<option value="1">Business Name</option>
<option value="2">Individual Owner</option>
</select>
If you are doing your if clause with one equals sign, Javascript will check if your element is set to the new value successfully.
Instead, when you do a comparison, use double equal signs (in your case)
if (document.getElementById("pcount").value == 1){
If anyone is looking for the JavaScript function here you go!
<script type="text/javascript">
function leaveChange() {
if (document.getElementById("pcount").value == 1){
document.getElementById("listedname").value = 1;
}
else if (document.getElementById("pcount").value != 1){
document.getElementById("listedname").value = "";
}
}
</script>
If I have an option list like the below:
<select name="optionList" id="optionList">
<optgroup label="optgroup1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</optgroup>
<optgroup label="optgroup2">
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</optgroup>
</select>
I know I can access the selectedIndex using:
document.getElementById('optionList').selectedIndex;
If I use the above though the selected index of 5 will be 4, 6 will be 5, 7 will be 6, etc
How can I tell where a selected item in an optgroup is?
In summary I'd like to be able to query something and get back its position in the optgroup so that 5 would return 0, 6 would return 1 etc...
This is a slightly complex task, because there is no native way to do it. I'm going to answer according to current browser standards: it's possible to do it in older browsers, but it is more work.
var select = document.getElementById('optionList'), // the <select> element
selectedIndex = select.selectedIndex, // 0-based index of which element in the <select> is selected
selectedElement = select.options[selectedIndex], // DOM element selected
optGroup = selectedElement.parentNode, // <optgroup> element
optGroupOptions = optGroup.children, // <option> elements in the <optgroup>
positionInOptGroup = Array.prototype.indexOf.call(optGroupOptions, selectedElement); // the selected <option>'s position in the <optgroup>
(jsFiddle)
Note that this will not work if the browser does not support Element#children (i.e. IE <9). You will have to filter the childNodes collection into an array at test against that. Similarly, it requires Array#indexOf, which also didn't exist in IE <9.
with pure javascript
var element = document.getElementById('optionList');
console.log(element.options[element.selectedIndex].parentNode.label);
Try this:
function indexOf(select) {
var options = select.options;
var selectedOption = options.item(select.selectedIndex);
var nodes = selectedOption.parentNode.children;
for (var i = 0; i < nodes.length; ++i) {
if (nodes[i] === selectedOption) {
return i;
}
}
return -1;
}
indexOf(document.getElementById('optionList'));
Working sample: http://jsfiddle.net/49R7k/1/
jQuery crossbrowser solution:
$('#optionList option:selected').index();
preview
I know that this is an old question and implementations may have changed, but I found that simple jQuery solution within the selector change event, e.g.
$(document).on('change', ".cmilestoneTaskSelector", function(e)
{
alert($(this.options[this.selectedIndex]).index());
.....
Tested in both Firefox and Chrome.