I have a page that creates a number of inputs based on the user's selection of how many to create:
select id="noOfDirectors" name="amount" onchange="addInput();">
<option value="">How Many Directors</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>
<option value="8" >8</option>
<option value="9" >9</option>
<option value="10" >10</option>
</select>
<div id="inputs"></div><br/>
<button id="nod" onclick="return false">Submit</button>
The .js file creates the forms:
function addInput(){
noOfDirectors = $('#noOfDirectors').val();
var inputs = $('#inputs').empty();
inputs.innerHTML = "";
for(i = 0; i < noOfDirectors; i++) {
inputs.append('Director '+ (i+1) +' Name: <input type="text" name="directorName[' + i + ']" /><br/>Director '+ (i+1) +' Customer Number: <input type="text" name="directorECN['+i+']" /><br/><br/>');
}
$("#nod").show();
directors = $('[name^=directorECN]').map(function(i) {
//return this.name;
return this.value; // for real values of input
}).get();
}
$(document).ready(function() {
$('#nod').click(function() {
console.log(directors);
});
});
Now, I want to take each of those directorECN['+i+'] input names and add them to a globally declared array:
var directors = new Array ();
I am having a hard time figuring out a syntax that works without hard coding 10 (0-9) of each of the possible input names. Is there an easier way to do this?
Here is my UPDATED JSFiddle
Updated my JS above. Console is printing [""]
You can use .map() to get the array from name attribute of elements returned by Attribute Starts With Selector [name^=”value”].
var directors = $('[name^=directorECN]').map(function(i) {
//return this.name;
return this.value; // for real values of input
}).get();
Use .map() function over the attribute starts with selector [attribute^="value"]
var directors = $('[name^="directorECN"]').map(function () {
return this.name //to get value use this.value
}).get();
Updated Fiddle
Related
Im trying to get value from checkbox that has been checked, but for some reason the value is shuffled in some weird pattern
here jsfiddle (try to check fruit and then click disable)
<input id="checkedTree" type="text"/>
<select id="test-select" onchange="getCheckedTree()">
<option value="1" data-section="fruit">Banana</option>
<option value="2" data-section="fruit">Apple</option>
<option value="3" data-section="fruit">Avocado</option>
<option value="4" data-section="fruit">Pineapple</option>
<option value="5" data-section="fruit">PenPineappleApplePen</option>
<option value="6" data-section="animal">Tiger</option>
<option value="7" data-section="animal">Lion</option>
<option value="8" data-section="animal">Pitbull</option>
<option value="9" data-section="animal">OrangUtan</option>
<option value="10" data-section="animal">Marsupilami Yellow cartoon</option>
</select>
I need to know why is it happened, and how to fix it. i do know the other way to get proper value like this. But for my project case i need "for" method
Update 1-> update jsfiddle
Values shuffled because you are getting the input array index checkedText.value = selectobject[z].value; knowing that at the change event the order of your hidden inputs change which causes the wrong values . (you can check by setting test-select display :block after page loding )
Above a working snippet :
note that you can passe directly value (1,2,3.. ) to the checkedTree input to disable directly inputs .
$( document ).ready(function() {
var $select = $('#test-select');
$select.treeMultiselect({
enableSelectAll: true,
sortable: false,
searchable: true,
startCollapse: true
});
});
function getCheckedTree(){
var tempCtr=0;
var $checkedText = $("#checkedTree");
var selectobject = $("[id*=treemultiselect-0-]:checked");
$checkedText.val("");
for(i=0;i<selectobject.length;i++) {
if(tempCtr==0){
tempCtr=1;
$checkedText.val($(selectobject[i]).parent().data("value"));
}else{
$checkedText.val($checkedText.val() + $(selectobject[i]).parent().data("value"));
}
}
}
function funcDis(){
var $checkedText = $("#checkedTree");
if($checkedText.val().length>0) {
$checkedText.val().split("").forEach(function(val){
$(".tree-multiselect .item[data-value="+val+"] input").prop('disabled', true);
$("#test-select option[value="+val+"]").prop('disabled', true);
})
};
}
function enableAll(){
$(".tree-multiselect input").each(function(idx){
$(this).prop('disabled', false);
var val = $(this).parent().data("value");
$("#test-select option[value="+val+"]").prop('disabled', false);
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link href="//cdn.rawgit.com/patosai/tree-multiselect/v2.1.3/dist/jquery.tree-multiselect.min.css" rel="stylesheet"/>
<script src="//cdn.rawgit.com/patosai/tree-multiselect/v2.1.3/dist/jquery.tree-multiselect.min.js"></script>
<input id="checkedTree" type="text"/> <button onclick="funcDis()">disable</button><button onclick="enableAll()">enable all</button>
<select id="test-select" onchange="getCheckedTree()">
<option value="1" data-section="fruit">Banana</option>
<option value="2" data-section="fruit">Apple</option>
<option value="3" data-section="fruit">Avocado</option>
<option value="4" data-section="fruit">Pineapple</option>
<option value="5" data-section="fruit">PenPineappleApplePen</option>
<option value="6" data-section="animal">Tiger</option>
<option value="7" data-section="animal">Lion</option>
<option value="8" data-section="animal">Pitbull</option>
<option value="9" data-section="animal">OrangUtan</option>
<option value="10" data-section="animal">Marsupilami Yellow cartoon</option>
</select>
PS:You can pass dirctly an array of value to funcDis and disable input at start up .
That's all ,I fiddle if you want.
I have a simple form with some options in it which are disabled and greyed out by default.
<select name="template" id="template" size="1" >
<option disabled selected value="1" name="1" id="1" class="bold-option">Mango</option>
<option class="select1"></option>
<option disabled selected value="2" class="bold-option" >Apple</option>
<option disabled selected value="3" class="bold-option">Pineapple</option>
<option disabled selected value="4" class="bold-option">Brocolli</option>
<option disabled selected value="5" class="bold-option">Peach</option>
<option disabled selected value="6" class="bold-option">Strawberry</option>
</select>
The idea behind it is that i want multiple variables which are defined by JQuery are getting imported into the select1 option for example, so the items that are linked to Select1 are listed below Mango.
I've made a var :
var issueTemplates = [
{'subject': 'This is a mango'}
];
Now i want to add this variable into the Option value beneath (or linked) to the Mango option within the select. I've looked into the append function but i cant seem to figure out how to get this straight.
I've made a select request in jquery which adds the subject in the dropdown form. But i want to have it beneath the Mango option..
This is de code
issueTemplates.forEach(function(item, idx) {
$("select[id='template']").append('<option value="' + idx + '">' + item.subject + '</option>');
This will get you started. If you have an array of additional options, you can iterate through the select element and load by index -1.
$(document).ready(function() {
var fruit = ['mango', 'apple', 'pineapple', 'brocolli', 'peach', 'strawberry']
$('#template option').each(function() {
val = $(this).val();
$(this).after('<Option val = ' + val + '>This is a ' + fruit[val - 1] + '</option>');
});
console.log($('#template option'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="template" id="template" size="1">
<option disabled selected value="1" name="1" id="1" class="bold-option">Mango</option>
<option disabled selected value="2" class="bold-option">Apple</option>
<option disabled selected value="3" class="bold-option">Pineapple</option>
<option disabled selected value="4" class="bold-option">Brocolli</option>
<option disabled selected value="5" class="bold-option">Peach</option>
<option disabled selected value="6" class="bold-option">Strawberry</option>
</select>
I have an Adobe form that will allow my customers to select services by inputting their initials. How do I get the "total" field to show the total price for the services selected based on the user's selection using JavaScript?
I.E.: I have 3 optional services that a customer can select (one has to be selected, the other to are optional add-ons).
If I understand your question, you want to have an input that store the total price of selected services. So try something like this:
var service1 = document.querySelector('#service1');
var service2 = document.querySelector('#service2');
var total = document.querySelector('#total');
service1.addEventListener('change', function (e) {
var currentPrice = service1.options[service1.selectedIndex].getAttribute('data-price');
var service2Price = service2.options[service2.selectedIndex].getAttribute('data-price');
total.value = parseInt(currentPrice) + parseInt(service2Price);
});
service2.addEventListener('change', function (e) {
var currentPrice = service2.options[service2.selectedIndex].getAttribute('data-price');
var service1Price = service1.options[service1.selectedIndex].getAttribute('data-price');
total.value = parseInt(currentPrice) + parseInt(service1Price);
});
<select id="service1">
<option value="1" data-price="50">Service 1</option>
<option value="2" data-price="100">Service 2</option>
<option value="3" data-price="150">Service 3</option>
</select>
<select id="service2">
<option value="1" data-price="25">Service 1</option>
<option value="2" data-price="75">Service 2</option>
<option value="3" data-price="125">Service 3</option>
</select>
<input type="number" placeholder="Total" id="total" />
I have a form that looks like this:
<form>
<input name="foo" value="1" />
<input name="bar[1]" value="a" />
<input name="bar[2]" value="b" />
<input name="bar[3]" value="c" />
<select name="test" multiple>
<option value="1" selected>a</option>
<option value="2" selected>b</option>
<option value="3" selected>c</option>
</select>
</form>
I can serialize the form like this:
$('form').serialize();
Which produces:
"foo=1&bar%5B1%5D=a&bar%5B2%5D=b&bar%5B3%5D=c&test=1&test=2&test=3"
I would like to serialize the select elements as dictionaries, producing this instead:
"foo=1&bar%5B1%5D=a&bar%5B2%5D=b&bar%5B3%5D=c&test%5B1%5D=a&test%5B2%5D=b&test%5B3%5D=c"
This is what I have so far:
function serializeSelectListAsDictionary() {
var name = $(this).attr('name'),
obj = {};
if (!$(this).is('select') || !name) {
return '';
}
$(this).children('option:selected').each(function() {
var key = name + '[' + $(this).val() + ']',
value = $(this).html();
obj[key] = value;
});
return $.param(obj);
}
$.fn.serializeDictionary = function() {
var serialized;
if (this.is('select')) {
return serializeSelectListAsDictionary.apply(this);
}
serialized = this.serialize();
this.find('select').each(function() {
serialized = serialized.replace($(this).serialize(), serializeSelectListAsDictionary.apply(this));
});
return serialized;
};
This works well enough when I call it like this:
$('form').serializeDictionary();
But a problem arises when I try to select multiple elements. Say I added another select element to the form:
<form>
<input name="foo" value="1" />
<input name="bar[1]" value="a" />
<input name="bar[2]" value="b" />
<input name="bar[3]" value="c" />
<select name="test" multiple>
<option value="1" selected>a</option>
<option value="2" selected>b</option>
<option value="3" selected>c</option>
</select>
<select name="blah" multiple>
<option value="4" selected>d</option>
<option value="5" selected>e</option>
<option value="6" selected>f</option>
</select>
</form>
Then if I call my extension method like this:
$('select').serializeDictionary();
It produces:
"test%5B1%5D=a&test%5B2%5D=b&test%5B3%5D=c&test%5B4%5D=d&test%5B5%5D=e&test%5B6%5D=f"
The output should look like this:
"test%5B1%5D=a&test%5B2%5D=b&test%5B3%5D=c&blah%5B4%5D=d&blah%5B5%5D=e&blah%5B6%5D=f"
I think my serializeSelectListAsDictionary function is only being called on the first element, but I'm not sure how to fix this.
Fiddle: http://jsfiddle.net/t5aze4r9/1
The problem is on the serializeDictionary function. It assumes that it will only receive one element to serialize. It works in the case of $('form').serializeDictionary(); because it only matches one form element. But if you had two form you'll see the same issue as with $('select').serializeDictionary();.
The issue shows up when the selector is matching more than one element because you are only serializing the first one. You need some kind of iteration over the matched elements.
Here is a proposal that tries to keep as much as possible your code structure:
$.fn.serializeDictionary = function() {
var serialized = this.serialize();
// Here is the key! You need to iterate over all the matched elements.
this.each(function() {
if ($(this).is('select')) {
serialized = serialized.replace($(this).serialize(), serializeSelectListAsDictionary.apply(this));
} else {
$(this).find('select').each(function() {
serialized = serialized.replace($(this).serialize(), serializeSelectListAsDictionary.apply(this));
});
}
});
return serialized;
};
See updated code.
Good morning. I have a form that is divided into numbered sections. Sometimes I need to disable some of these sections by using their section numbers. Right now when the function receives an array of section numbers I run a loop to collect them one-by-one. Is there a better, more efficient way of collecting numbered sections by their section numbers with jQuery?
HTML:
<div id="frameContent">
<div id="section1">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
<div id="section2">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
<div id="section3"><select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select></div>
<div id="section4">
<select>
<option value="1" selected="selected">empty (default)</option>
<option value="2" selected="selected">foo</option>
<option value="3" selected="selected">bar</option>
</select>
</div>
</div>
JS:
var toggleFormSections = function(frameContent, sectionNumbers, enable) {
// init empty selector
var sections = $();
// collect sections
for(var i = 0; i < sectionNumbers.length; i++) {
var section = frameContent.find('div#section' + sectionNumbers[i]);
sections = sections.add(section);
}
// disable/enable sections and elements within
if(sections.length > 0) {
if(enable) {
sections.find('select').prop('disabled', false);
} else {
sections.find('select').prop('disabled', 'disabled');
}
}
}
// usage:
var frameContent = $('#frameContent');
toggleFormSections(frameContent, [2,3], false);
Link to FIDDLE
http://jsfiddle.net/XZ9fT/3/
You can easily use jQuery's each to loop through the index elements, no need to check it's length. I'm not quite sure, why you want the enabled flag. Since you can call it with an empty array to enable everything. This would make it even shorter.
$.each(sectionNumbers, function(i) {
if(enable) {
frameContent.find('div#section' + sectionNumbers[i] + ' select').prop('disabled', false)
} else {
frameContent.find('div#section' + sectionNumbers[i] + ' select').prop('disabled', 'disabled');
}
});
One way will be
var toggleFormSections = function(frameContent, sectionNumbers, enable) {
// init empty selector
var sections = [];
// collect sections
for(var i = 0; i < sectionNumbers.length; i++) {
sections.push('#section' + sectionNumbers[i]);
}
sections = $(sections.join(', '))
sections.find('select').prop('disabled', !enable);
}
Demo: Fiddle