On click of a button the code will check that "select all" is selected or individually selected. Now the problem is if one selects any "select all" checkbox and if then unchecked any option, then these unchecked values are passed instead of checked ones.
$("#next").click(function () {
debugger
$(".show").show();
$("#next").hide();
if ($('.checkbox2 ul.dropdown-content li input[type=checkbox]').first().is(':checked') == true){
$.each(budata, function (key, value) {
arr.push(key);
});
}else {
debugger
arr = $('option[name=BU]:checked').map(function () {
return this.value;
}).get();
}
var bu = arr.join(',');
HTML CODE
<div class="checkbox2">
<div class="input-field col s6">
<select id="dropdown1" multiple>
<option value="" disabled selected>Select BU</option>
</select>
<label>BU</label>
</div>
</div>
AJAX CALl for BU values(Checkbox values)
var data = {};
data.dateFrom = $("#dateFrom").val();
data.BU = $("#dropdown1").val();
data.Location = $("#Location").val();
data.Type = $("#dropdown").val();
$.ajax({
type: 'POST',
url: ServiceURL + 'MaterialClearance/getBU/',
async: false,
success: function (data) {
$('#dropdown1').html('<option id="selectall" name="selectall" value="selectall" ">(Select All)</option>');
if (data.length > 0) {
for (i = 0; i < data.length; i++) {
budata[data[i].BU] = 0;
$('#dropdown1').append('<option name="BU" value="' + data[i].BU + '">' + data[i].BU + '</option>')
}
}
$('#dropdown1').material_select();
}
});
CODE for select all nd individual checked checkbox
$('.checkbox2 ul.dropdown-content li').click(function () {
debugger
if ($('.checkbox2 ul.dropdown-content li').first().is(".selected")) {
$('.checkbox2 ul.dropdown-content li:not(:first-child)').each(function (index) {
$(this).find("input[type=checkbox]").prop("checked", $('.checkbox2 ul.dropdown-content li').first().find("input[type=checkbox]").prop("checked"));
});
}
else {
alert($('option[name=BU]:checked'));
$('.checkbox2 ul.dropdown-content li input[type=checkbox]').first().prop("checked", false);
alert($('option[name=BU]:checked'));
}
});
Related
I'm new to JS
I currently have two functions.
The both work as they should.
However, I cannot use the value from the first document function and fire the onchange event in the second and use the selected value.
I would like the selected value from the first script to fire the onchange event in the second script.
Please help!
Html:
<td>
<input type="text" name="product[]" placeholder="Product"
class="product"
onfocus="javascript:$(this).autocomplete('search','');">
</td>
1: Auto complete:
$(function () {
var validOptions = <? echo $get_product_names ?>;
previousValue = "";
$(".product")
.autocomplete({
source: validOptions,
select: function( event, ui ) {alert($(this).val())},
minLength: 0
}).keyup(function () {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
}).click(function () {
$(this).autocomplete('search', $(this).val())
});
});
2nd: Generate Pricing:
$(document).on('change', '.product, .width, .drop', function () {
var product = $(".product", $(this).parent().parent()).val();
//alert(product);
var width = $(".width", $(this).parent().parent()).val();
var drop = $(".drop", $(this).parent().parent()).val();
var sub_total = $(".total", $(this).parent().parent());
if (product === "" || width === "" || drop === "") {
var parent = sub_total.val(0);
}
if (product !== "" && width !== "" && drop !== "") {
$.ajax({
url: "#",
method: "POST",
data: {
"product": product,
"width": width,
"drop": drop
},
success: function (data) {
if (data === "") {
var parent = sub_total.val(0);
}
else {
var parent = sub_total.val(data);
}
calculate(parent);
}
});
}
});
For future readers:
I switched over to chosen
My code looks like this now.
<td>
<select data-placeholder="Choose Type" name="product[]"
class="product chosen-select" tabindex="2"
style="width: 150px">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
js:
//trigger product change
$('.product').click(function () {
$('.product').trigger("chosen:updated");
});
$(document).on('change', '.product, .width, .drop', function () {
var product = $(".product", $(this).parent().parent()).val();
//alert(product);
var width = $(".width", $(this).parent().parent()).val();
var drop = $(".drop", $(this).parent().parent()).val();
var sub_total = $(".total", $(this).parent().parent());
if (product === "" || width === "" || drop === "") {
var parent = sub_total.val(0);
}
if (product !== "" && width !== "" && drop !== "") {
$.ajax({
url: "#",
method: "POST",
data: {
"product": product,
"width": width,
"drop": drop
},
success: function (data) {
if (data === "") {
var parent = sub_total.val(0);
}
else {
var parent = sub_total.val(data);
}
calculate(parent);
}
});
}
});
I am trying to create a search form using jquery for following tasks to do:
A user can upload file or input text into the text area or select option from the drop-down menu but these options will appear based on the selection of 1st drop-down menu.
The user can clone this form number of times but not more than max options of the 1st drop-down menu.
The user can remove form < max options from the 1st drop-down menu.
But problems are:
Task 1 is working only on the original form but not in cloned one.I think due to the tag id, it only does the task for original one, so how can I do that for multiple occasion?
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$('#alarm_action').change(function (e) {
if ($("#alarm_action").val() == "listofcompany") {
$('#filefield').show();
$("#myTextarea").hide();
$("#showForProg").hide();
} else if ($("#alarm_action").val() == "runprogram") {
$('#filefield').hide();
$("#myTextarea").hide();
$("#showForProg").show();
} else {
$('#filefield').hide();
$("#myTextarea").show();
$("#showForProg").hide();
}
});
$(addButton).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication" name="searchtype" id="alarm_action" required>\
<option value="cityname">City Name</option>\
<option value="listofcompany">Company</option>\
<option value="runprogram">Run Program</option></select>\
<body onload="setProg();">\
<select name="searchtermorg" id="showForProg" style="display: none;"></select>\
</body>\
<input id="filefield" type="file" name="foofile" style="display: none;"/>\
<textarea id="myTextarea" name="something" ></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).find('option:selected').text()+' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type !=""){
if (query.type == "listofcompany") {
query.value =$(field).find('#filefield').val();
} else if (query.type == "runprogram") {
query.value =$(field).find('#showForProg').val();
} else {
query.value =$(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else{
slectedall=false;
}
});
var url = window.location.href;
url+="/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() ===""){
fillupfield=false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
var progarray = ['Python','Java','R'];
function setProg() {
var newOptions=progarray;
var newValues=progarray;
selectField = document.getElementById("showForProg");
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++)
{
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication" name='searchtype' id="alarm_action" required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body onload="setProg();">
<select name="searchtermorg" id="showForProg" style="display: none;"></select>
</body>
<input id="filefield" type="file" name="foofile" style="display: none;"/>
<textarea id="myTextarea" name="something"></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Can anybody help me to fix these problems? thank you
Issues with our current code:
In a valid HTML, idof an element should be unique. But here you are repeating the element id every time you clone the elements. Use class instead of id.
Use $.on to bind events to elements which are added dynamically (eg, the dropdown change event)
Spaghetti code which is not maintainable - I've tried cleaning up a bit. But there is a lot of scope for clean up.
I've fixed the issue which you have mentioned by fixing the above-mentioned points. But as I said, there is a lot of clean-up to be done before this could be used in a project.
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
var progarray = ['Python', 'Java', 'R'];
wrapper.append($("#content-template").html());
//alert($(".showForProg").length);
setProg($(".showForProg"));
$(document).on('change', '.alarm_action', function(e) {
var $container = $(this).parents('.form-field');
if ($(this).val() == "listofcompany") {
$('.filefield', $container).show();
$(".myTextarea", $container).hide();
$(".showForProg", $container).hide();
} else if ($(this).val() == "runprogram") {
$('.filefield', $container).hide();
$(".myTextarea", $container).hide();
$(".showForProg", $container).show();
} else {
$('.filefield', $container).hide();
$(".myTextarea", $container).show();
$(".showForProg", $container).hide();
}
});
$(addButton).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
wrapper.append($("#content-template").html());
setProg($(".showForProg").last());
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change', 'select.removeDuplication', function(e) {
e.preventDefault();
var cI = $(this);
var others = $('select.removeDuplication').not(cI);
$.each(others, function() {
if ($(cI).val() == $(this).val() && $(cI).val() != "") {
$(cI).val('');
alert($(this).find('option:selected').text() + ' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall = true;
var fillupfield = true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type != "") {
if (query.type == "listofcompany") {
query.value = $(field).find(',filefield').val();
} else if (query.type == "runprogram") {
query.value = $(field).find(',showForProg').val();
} else {
query.value = $(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else {
slectedall = false;
}
});
var url = window.location.href;
url += "/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() === "") {
fillupfield = false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall === false) {
alert('Please select option.');
} else {
if (fillupfield === false) {
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
function setProg($programDropdown) {
$.each(progarray , function(key, value) {
$programDropdown
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<script type="text/template" id="content-template">
<div class="repeat-container">
<div class="form-field">
<select class="alarm_action removeDuplication" name='searchtype' required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body>
<select name="searchtermorg" class="showForProg" style="display: none;"></select>
</body>
<input class="filefield" type="file" name="foofile" style="display: none;" />
<textarea class="myTextarea" name="something"></textarea>
</div>
</div>
</script>
I am trying to disable a select option if selected on a previous row say my html table creates a row if the value of a last rows text box are filled and select is changed what i was trying to do was if the select option is selected before then on new row created the select option should be disabled when i add the code of disable then the new row is not created.
Demo Fiddle with select code
Demo Fiddle with out select code
$('#results').append('<table width="100%" border="1" cellspacing="0" cellpadding="5" id="productanddates" class="border"> <tr><td> <input type="text" name="to1" id="to1" value="" /> </td> <td> <select class="dd" name="Phonenumberdd1" id="Phonenumberdd1"> <option value="test">test </option><option value="test1">test1 </option><option value="test2">test 2</option></select></td> <td> <input type="text" name="renewal_by1" id="renewal_by1" /> </td> <td> <input type="text" name="Renivaul_to1" id="Renivaul_to1" value="" /> </td></TR></TABLE>');
//*******the select code if this is removed all works fine******?//
setTimeout(function () {
var $selects = $('select');
$selects.on('change', function () {
$("option", $selects).prop("disabled", false);
$selects.each(function () {
var $select = $(this),
$options = $selects.not($select).find('option'),
selectedText = $select.children('option:selected').text();
$options.each(function () {
if ($(this).text() == selectedText) $(this).prop("disabled", true);
});
});
});
$selects.eq(0).trigger('change');
}, 99);
$('#results').on('focus', ':input', function () {
$(this).closest('tr').filter(function () {
return !$(this).data('saved');
})
.find(':input').each(function () {
$(this).data('value', this.value);
$(this).closest('tr').data('saved', true);
});
})
.on('input change', ':input', function () {
$(this).data('filled', this.value != $(this).data('value'))
var tr = $(this).closest('tr');
all = tr.find(':input'),
fld = all.filter(function () {
return $(this).data('filled');
});
if (all.length == fld.length) {
if (!tr.data('done')) {
$('#buttonclck')[0].click();
tr.data('done', true);
}
} else {
if (tr.data('done')) {
tr.next('tr').remove();
tr.data('done', false);
}
}
});
$('#buttonclck').on('click', function () {
var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");
var cloned = lastRow.clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
var regIdMatch = /^(.+)(\d+)$/;
var aIdParts = id.match(regIdMatch);
var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
$(this).attr('id', newId);
$(this).attr('name', newId);
});
cloned.find("input[type='text']").val('');
cloned.insertAfter(lastRow);
});
$('#results').on('change', '.dd', function (e) {
var data = "dummy data";
$(this).closest('td').prev().find('input').val(data).trigger('input');
$(this).closest('td').next().find('input').val(data).trigger('input');
});
The following code, executed once a new row is added, should iterate through the previous rows and disable in the new row values of select that have already been used:
var prevRows = cloned.siblings();
cloned.find('select option').each(function(index,option) {
prevRows.each(function(i,tr) {
option.value !== $('select', tr).val() || $(option).prop('disabled', true);
});
});
DEMOS
DEMO 1
DEMO 2
DEMO 3
good day to all, i have this script where i am appending checkbox when the add button is click. now my problem is that when i add two checkbox, when i click the second checkbox it triggers the first checkbox not the second checkbox.
here's my code.
$(document).ready(function () {
var TempCounter = parseInt($('input[name^="TempID"]').val());
var count = TempCounter;
var ajaxCount = count + 1;
var reqCount = TempCounter;
$('#addButton').click(function(e) {
$("#ApprovalRequestor").append('<div><input style="margin-left:20px;" type="checkbox" id="requestorManagerChecked'+count+'" name="requestorManager['+count+']" > </input>'
+ '<span>'+document.getElementById(document.getElementById('selectOtherRequestor').value).innerHTML+'</span>Delete <input type="hidden" value="'+$('#selectOtherRequestor').val()+'" id="ApproversID" name="ApproversID['+count+']"> </input>'
+ '<input type="hidden" id="TempCount" name="TempCount" value="'+count+'"/>'
+ '<input type="hidden" id="levelID" name="levelID['+count+']" value="1"> </input> </div>');
$('#requestorManagerChecked'+count+' ').change(function() {
if($('#requestorManagerChecked'+reqCount+' ').is(":checked") ) {
$('#requestorManagerChecked'+reqCount+' ').val(1);
alert('requestorManagerChecked'+reqCount+' ');
alert($('#requestorManagerChecked'+reqCount+' ').val() );
}
else {
$('#requestorManagerChecked'+reqCount+' ').val(0);
alert($('#requestorManagerChecked'+reqCount+' ').val() );
}
});
$.ajax({
type: 'post',
url: 'mis.php/fileApproversListController/getCounter',
data: 'variable='+ajaxCount,
success: function(data) {
$('#Count').html(data);
}
});
reqCount = count;
ajaxCount++;
count++;
});
here's my controller
function SaveApprovers() {
$this->load->model('new_development_model');
$requestType = $this->input->post('requestTypeID');
$ApproversLists = $this->input->get_post('Approvers');
for($ctr = 0; $ctr <= $this->input->get_post('counter'); $ctr++) {
$ApproversLists[$ctr]['ApproversLevel'];
$ApproversLists[$ctr]['Required'];
$ApproversLists[$ctr]['ApproversID'];
$Remark = $this->input->get_post('Remarks');
$this->new_development_model->ApproversList($ApproversLists[$ctr]['ApproversLevel'], $ApproversLists[$ctr]['Required'],$ApproversLists[$ctr]['ApproversID'],$Remark);
}
}
I need to display the selected sub-categories (multi) in the below div and also in some situations I need to close the div elements that are selected wrongly from the select box, so that I can add and delete elements to the div (by the above selectbox).
Even I made the similar code, but its not working for multi selection.
Briefly, I need the selected categories (multi) with close buttons in the below div.
<script type="text/javascript">
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = catogery.options[catogery.selectedIndex].value;
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
</script>
<body>
<form action="#" enctype="multipart/form-data">
<select name="cat" id="cat" onchange="selectlist();" multiple="multiple">
<option>Select subcatogery</option>
<option value="fashion">Fashion</option>
<option value="jewelry">Jewelry</option>
<option value="dresses">dresses</option>
<option value="shirts">Shirts</option>
<option value="diamonds">Diamonds</option>
</select>
<div id="check">
</div></form>
</body>
</html>
Loop over the options and check if they are selected, something like this:
function selectlist() {
var checkboxhome = document.getElementById("check");
var category = document.getElementById("cat");
checkboxhome.innerHTML = '';
for (var i = 0; i < category.options.length; i++) {
if (category[i].selected) {
checkboxhome.innerHTML += "<p>" + category.options[i].value + "</p>";
}
}
}
Here is a fiddle of what could work for you: http://jsfiddle.net/maniator/W6gnX/
Javascript:
function selectlist() {
checkboxhome = document.getElementById("check");
catogery = document.getElementById("cat");
value = getMultiple(catogery);
checkboxhome.innerHTML = "<br/> <p>" + value + "</p>";
}
function getMultiple(ob)
{
var arSelected = new Array(), length = ob.length, i = 0, indexes = [];
while (ob.selectedIndex != -1 && i < length)
{
if (ob.selectedIndex != 0 && !in_array(ob.selectedIndex, indexes)) {
indexes.push(ob.selectedIndex)
arSelected.push(ob.options[ob.selectedIndex].value);
}
ob.options[ob.selectedIndex].selected = false;
i++;
}
var count = 0;
while(count < indexes.length){
ob.options[indexes[count]].selected = true;
count ++;
}
return arSelected;
}
function in_array(needle, haystack)
{
for(var key in haystack)
{
if(needle === haystack[key])
{
return true;
}
}
return false;
}