Double click on the selected item in dropdown - javascript

I am having problem that as i select an item from drop-down the list box does not comes i need to click again on the selected item item in drop-down to get the list appear..that means i need a double click on the item in drop-down.
This is my html
<script>
function ShowHideListBox(e) {
e.stopPropagation()
e.preventDefault()
var IsOpen = $('#listbox').attr('IsOpen')
if (IsOpen == "false") {
ShowList(e)
}
else {
HideList(e)
}
}
function ShowList(elem) {
$('#listbox').attr('IsOpen', 'true')
$('#listbox').show()
}
function HideList(elem) {
$('#listbox').attr('IsOpen', 'false')
$('#listbox').hide()
}
</script>
<form name="myform" id="myForm">
<select id="dropdown1" onclick="return ShowHideListBox(event)"></select>
<select id="listbox" multiple style="display:none; cursor:default;" isopen="false"></select>
</form>
My js file
$(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
/* $('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
*/
//$.each(usedNames, function(index, value) {
// $('<option>', {
// text: value['name'],
// value: index
// }).appendTo('#dropdown1');
//});
/* $('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox'); */
$('#dropdown1').change(function() {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
// var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] == selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$("#listbox").css("width","500px")
$("#listbox").css("height","300px")
$('#listbox').append(optionHtml); return false;
}
});
});
});
}
});
});

You are sending the event and passing it to the Showlist function
You need to send the target Also remove the e.stopPropagation(); e.preventDefault()
<script>
function ShowHideListBox(e) {
var IsOpen = $('#listbox').attr('IsOpen')
if (IsOpen == "false") {
ShowList(e.target)
}
else {
HideList(e.target)
}
}
function ShowList(elem) {
$('#listbox').attr('IsOpen', 'true')
$('#listbox').show()
}
function HideList(elem) {
$('#listbox').attr('IsOpen', 'false')
$('#listbox').hide()
}
</script>
<form name="myform" id="myForm">
<select id="dropdown1" onclick="return ShowHideListBox(event)"></select>
<select id="listbox" multiple style="display:none; cursor:default;" isopen="false"></select>
</form>

Related

How to addClass if autocomplete input is empty?

I would like to know how to add a class if autocomplete input is empty? There's a function which autocompletes the address when putting the post code. If for example address_1 is empty, it adds the class form-control, else it adds the class sem-bordas.
I tried:
$('#input-address-1').on('change', function() {
if ($(this).val() == '') {
$(this).next().removeClass("form-control");
} else {
$(this).next().addClass("sem-bordas");
}
});
But without success.
Thats all the function
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});
$(document).on('input','#input-address-1', function() {
if ($(this).val() == '') {
$(this).next().addClass("sem-bordas");
} else {
$(this).next().removeClass("sem-bordas");
}
});
Let me explain, thats all my function to verify if the address exist or not
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});
Soon after putting the postcode and an address was not found, I would like to add a class to the fields that were not filled. The goal is to highlight fields that have not been filled
I found the solution
After
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
Put this code
if($.trim($('#input-address-1').val()) == ''){
$('#input-address-1').addClass('form-control');
}else {
$('#input-address-1').removeClass('form-control');
$('#input-address-1').addClass('sem-bordas');
}
Thanks everyone for helping. I think thats the solution

Embedding values using for loop

As I m having incremental values of attributes so i am ´following this method as you can see I hardcoded my attributes butI want to embed them in a loop..please tell how can i do that.. I am not able to achieve that...Thank you..
I m getting values in my dropdown from a json file in which i m having 20 attributes...When i click on particular value from dropdown ...the attributes related to that value are shown inside a list box..
My html
form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox"></select>
<!-- <input type="checkbox">-->
<br>
(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
/* $('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
*/
$.each(usedNames, function(index, value) {
$('<option>', {
text: value['name'],
value: index
}).appendTo('#dropdown1');
});
/* $('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox'); */
$('#dropdown1').change(function() {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] === selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
}
});
});
});
}
});
});
You can use a for loop to generate the option elements as all the attributes are incremental. Try this:
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] === selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
}
});
Working example
Note that this also builds the HTML as a single string and appends it to the DOM once for better performance.

How to add HTML text field with value from select list via Javascript

I have select list like this:
$.fn.optionTest = function(opts) {
var option = $.extend({}, $.fn.optionTest.defaults, opts);
$(this).change(function() {
option.holderObject = $(this);
if (option.clearOnChange) {
$(option.actionId).empty();
}
var val = $(this).val();
if ($.fn.optionTest.isArray(val)) {
$.fn.optionTest.parseArray(val, option);
} else {
var label = $(this).children("option:selected").eq(0).text();
$.fn.optionTest.parseContent(val, option, label);
}
$('.' + option.removeLinkOptions.class).click(function(event) {
$.fn.optionTest.removeRow(this, option);
event.preventDefault();
});
$("[type=date]").datepicker({
monthNamesShort: $.datepicker.regional["en"].monthNames,
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: "-116:+10",
});
return this;
});
};
$.fn.optionTest.isArray = function(val) {
return Object.prototype.toString.call(val) === '[object Array]';
};
$.fn.optionTest.defaults = {
clearOnChange: false,
actionId: '#action',
indexOptions: {
class: 'field-style field-split25 align-left'
},
rowOptions: {
class: 'certificates',
type: 'text',
name: 'CertificateType[]',
tag: 'ul'
},
CertNoOptions: {
name: 'CertNo[]',
type: 'text',
placeholder: 'Cert No.',
size: 20,
class: 'field-style field-split25 align-left'
},
PlaceofIssueOptions: {
name: 'PlaceofIssueCert[]',
type: 'text',
placeholder: 'Place of Issue',
size: 20,
class: 'field-style field-split25 align-left'
},
fromOptions: {
name: 'FromCert[]',
type: 'date',
placeholder: 'Date of Issue',
size: 20,
class: 'field-style field-split25 align-left'
},
toOptions: {
name: 'ToCert[]',
type: 'date',
placeholder: 'Date of Expire',
size: 20,
class: 'field-style field-split25 align-left'
},
labelOptions: {
class: 'field-style field-split25 align-left',
type: 'text'
},
removeLinkOptions: {
class: 'removeRow',
href: 'javascript:;'
}
};
$.fn.optionTest.parseArray = function(vals, options) {
var selectedOptions = options.holderObject.children("option:selected");
console.log(selectedOptions.eq(0).html());
$.each(vals, function(key, val) {
$.fn.optionTest.parseContent(val, options, selectedOptions.eq(key).text());
});
};
$.fn.optionTest.removeRow = function(elem, options) {
var row = $(elem).closest(".certificates");
row.remove();
$.fn.optionTest.updateRowIndex(options);
};
$.fn.optionTest.updateRowIndex = function(options) {
$("." + options.rowOptions.class).each(function(key, value) {
var index = key + 1;
$(value).attr('rowdataid', index);
$(value).children("." + options.indexOptions.class).html(index);
});
};
$.fn.optionTest.createColumn = function(content) {
var li = $('<li>');
return li.append(content);
}
$.fn.optionTest.parseContent = function(val, options, label) {
var index = $('.' + options.rowOptions.class).length + 1;
var rowData = $.extend({}, options.rowOptions);
var indexData = $.extend({}, options.indexOptions);
rowData.rowDataId = index;
var CertNoData = $.extend({}, options.CertNoOptions);
CertNoData.name = CertNoData.name;
var PlaceofIssueData = $.extend({}, options.PlaceofIssueOptions);
PlaceofIssueData.name = PlaceofIssueData.name;
var DateofIssueData = $.extend({}, options.DateofIssueOptions);
DateofIssueData.name = DateofIssueData.name;
var DateofExpireData = $.extend({}, options.DateofExpireOptions);
DateofExpireData.name = DateofExpireData.name;
var fromData = $.extend({}, options.fromOptions);
fromData.name = fromData.name;
var toData = $.extend({}, options.toOptions);
toData.name = toData.name;
var start_by = "<li><ul class='column'><li>";
var end_by = "</li></ul></li>";
var labelData = $.extend({}, options.labelOptions);
if ($('#' + rowData.id).length == 0) {
var tag = "<" + rowData.tag + ">";
delete rowData['tag'];
var row = $(tag, rowData);
var id = $('<li>', indexData).html(index);
//var label = $('<li>', labelData).html(label);
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
var CertNo = $.fn.optionTest.createColumn($("<input>", CertNoData));
CertNo = $(start_by + $(CertNo).html() + end_by);
var PlaceofIssue = $.fn.optionTest.createColumn($("<input>", PlaceofIssueData));
PlaceofIssue = $(start_by + $(PlaceofIssue).html() + end_by);
var DateofIssue = $.fn.optionTest.createColumn($("<input>", DateofIssueData));
DateofIssue = $(start_by + $(DateofIssue).html() + end_by);
var DateofExpire = $.fn.optionTest.createColumn($("<input>", DateofExpireData));
DateofExpire = $(start_by + $(DateofExpire).html() + end_by);
var from = $.fn.optionTest.createColumn($("<input>", fromData));
from = $(start_by + $(from).html() + end_by);
var to = $.fn.optionTest.createColumn($("<input>", toData));
to = $(start_by + $(to).html() + end_by);
var removeRow = $.fn.optionTest.createColumn($("<button>", options.removeLinkOptions).text("X"));
removeRow = $($(removeRow).html());
// row.append(label).append(CertNo).append(PlaceofIssue).append(from).append(to).append(removeRow);
row.append('<input type="hidden" name="RowCertificateType[]" value="' + val + '" />').append(label).append(CertNo).append(PlaceofIssue).append(from).append(to).append(removeRow);
$(options.actionId).append(row);
}
};
$(document).ready(function() {
$('#options').optionTest({
actionId: '.action2',
clearOnChange: false
});
});
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<fieldset class="fieldset-borders">
<legend>6. Certificates</legend>
<ul class="header">
<li>
<select id='options' name="CertificateType[]" class="field-style div-format align-left">
<option selected disabled value="0">Select certificates</option>
<option value="1">Foo</option>
<option value="2">Bar</option>
<option value="3">OTHER</option>
</select>
</li>
</ul>
<div class="action2" ></div>
</fieldset>
As you see after selecting any option from list It adding some fields. I need to add text field label with value that selected from options.
As in example I have 3 options:
Foo
Bar
OTHER
If I select Foo It should add fields like:
Foo [ ] [ ] [ ] [ ]
If I select Bar It should add fields like:
Bar [ ] [ ] [ ] [ ]
If I select OTHER It should generate only blank fields without value:
[ ] [ ] [ ] [ ] [ ]
For now It adding all blank fields for any selected option.
If I use:
var label = $('<li>', labelData).html(label);
Instead of:
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
It adding label field with value, but not editable, It's not text field and after adding OTHER It can't be changed.
Have you ideas how can I achieve correct syntax with If? Something like:
If (option selected = 'OTHER') {
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
}
else {
var label = $('<li>', labelData).html(label);
}
I cannot be certain that I understand your question, but I think what you want is for the selected label to display as the value in the first input field, unless the selected label is "OTHER", in which case the field should have no value property.
If this is correct, we could achieve this by extending our labelData object:
var labelData = $.extend({}, options.labelOptions, {
value: ((label === 'OTHER') ? '' : label)
});

How to fill multiple input fields from one a HREF

update
I need to be able to reference the XML from my actual XML document, i dont want it just var'd into jQuery...
How do i get the following behaviour to occur...
Searching the label input searches for both label and value, however, only omits results from each to their respective input field so typing Alabama shows Alabama - AL but only gives me Alabama in state and AL in value
also using
$.ajax({
type: "GET",
url: "states.xml", // change to full path of file on server
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function(data) {
alert("XML File could not be found");
}
});
instead of the var myXML
var myXml = '<?xml version="1.0" encoding="UTF-8"?><states><state label=Alabama value=AL country="US"><state label=Alaska value=AK country="US"></states>';
$(document).ready(function() {
var myArrLabel = [];
var myArrValue = [];
var myArrCountry = [];
function parseXml(xml){
$(xml).find("state").each(function(){
var a1=[], a2=[], a3=[];
a1.push($(this).attr("label"));
a2.push($(this).attr("value"));
a3.push($(this).attr("country"));
$.each(a1, function(i, el){
if($.inArray(el, myArrLabel) === -1) myArrLabel.push(el);
});
$.each(a2, function(i, el){
if($.inArray(el, myArrValue) === -1) myArrValue.push(el);
});
$.each(a3, function(i, el){
if($.inArray(el, myArrCountry) === -1) myArrCountry.push(el);
});
});
};
parseXml( myXml );
function fillIfUnique(box1, box2, attr1, attr2) {
var value1 = box1.val();
var valueItemsForLabel = $(myXml).find('state[' + attr1 + '="' + value1 + '"]');
if ( valueItemsForLabel.length ) {
var value2 = valueItemsForLabel.eq(0).attr( attr2 );
console.log( 'value2: ' + value2 );
var totalSame = $(myXml).find('state[' + attr1 + '="' + value1 + '"][' + attr2 + '="' + value2 + '"]');
if( valueItemsForLabel.length==totalSame.length ) {
box2.val( value2 );
} else {
box2.val( '' );
};
};
};
function setupAC() {
$("input#labelBox").autocomplete({
source: myArrLabel,
minLength: 1,
select: function(event, ui) {
$("input#labelBox").val(ui.item.value);
fillIfUnique($('#labelBox'), $('#valueBox'), 'label', 'value');
fillIfUnique($('#labelBox'), $('#countryBox'), 'label', 'country');
}
});
$("input#valueBox").autocomplete({
source: myArrValue,
minLength: 1,
select: function(event, ui) {
$("input#valueBox").val(ui.item.value);
fillIfUnique($('#valueBox'), $('#labelBox'), 'value', 'label');
fillIfUnique($('#valueBox'), $('#countryBox'), 'value', 'country');
}
});
$("input#countryBox").autocomplete({
source: myArrCountry,
minLength: 1,
select: function(event, ui) {
$("input#countryBox").val(ui.item.value);
fillIfUnique($('#countryBox'), $('#labelBox'), 'country', 'label');
fillIfUnique($('#countryBox'), $('#valueBox'), 'country', 'value');
}
});
};
setupAC();
});
</script>
<form name="search_form" id="searchForm" method="GET">
<p><label for="labelBox">Label Search</label>
<input type="text" id="labelBox" name="labelBox" /></p>
<p><label for="valueBox">Value Search</label> <input type="text" id="valueBox" name="valueBox" /></p>
<p><label for="countryBox">Country Search</label> <input type="text" id="countryBox" name="countryBox" /></p>
<p><label></label> <button name="searchKeyword" id="searchKeyword">Submit</button></p>
</form>
We have to follow this logic: After autocomplete selects value, we have to to check if values for other two fields are unique in their scope. For example, selecting country-code CA (xml value attribute) has unique label California, as well as unique country US. If the values is not unique, than we erase that input value. The checking function name is fillIfUnique(), take a look at this Fiddle.
HTML used:
<h3>jQuery Autocomplete using XML as Data Source Example</h3>
<form name="search_form" id="searchForm" method="GET">
<p><label for="labelBox">Label Search</label>
<input type="text" id="labelBox" name="labelBox" /></p>
<p><label for="valueBox">Value Search</label> <input type="text" id="valueBox" name="valueBox" /></p>
<p><label for="countryBox">Country Search</label> <input type="text" id="countryBox" name="countryBox" /></p>
<p><label></label> <button name="searchKeyword" id="searchKeyword">Submit</button></p>
</form>
Script:
$(document).ready(function() {
var myArrLabel = [];
var myArrValue = [];
var myArrCountry = [];
function parseXml(xml){
$(xml).find("state").each(function(){
var a1=[], a2=[], a3=[];
a1.push($(this).attr("label"));
a2.push($(this).attr("value"));
a3.push($(this).attr("country"));
$.each(a1, function(i, el){
if($.inArray(el, myArrLabel) === -1) myArrLabel.push(el);
});
$.each(a2, function(i, el){
if($.inArray(el, myArrValue) === -1) myArrValue.push(el);
});
$.each(a3, function(i, el){
if($.inArray(el, myArrCountry) === -1) myArrCountry.push(el);
});
});
};
parseXml( myXml );
function fillIfUnique(box1, box2, attr1, attr2) {
var value1 = box1.val();
var valueItemsForLabel = $(myXml).find('state[' + attr1 + '="' + value1 + '"]');
if ( valueItemsForLabel.length ) {
var value2 = valueItemsForLabel.eq(0).attr( attr2 );
console.log( 'value2: ' + value2 );
var totalSame = $(myXml).find('state[' + attr1 + '="' + value1 + '"][' + attr2 + '="' + value2 + '"]');
if( valueItemsForLabel.length==totalSame.length ) {
box2.val( value2 );
} else {
box2.val( '' );
};
};
};
function setupAC() {
$("input#labelBox").autocomplete({
source: myArrLabel,
minLength: 1,
select: function(event, ui) {
$("input#labelBox").val(ui.item.value);
fillIfUnique($('#labelBox'), $('#valueBox'), 'label', 'value');
fillIfUnique($('#labelBox'), $('#countryBox'), 'label', 'country');
}
});
$("input#valueBox").autocomplete({
source: myArrValue,
minLength: 1,
select: function(event, ui) {
$("input#valueBox").val(ui.item.value);
fillIfUnique($('#valueBox'), $('#labelBox'), 'value', 'label');
fillIfUnique($('#valueBox'), $('#countryBox'), 'value', 'country');
}
});
$("input#countryBox").autocomplete({
source: myArrCountry,
minLength: 1,
select: function(event, ui) {
$("input#countryBox").val(ui.item.value);
fillIfUnique($('#countryBox'), $('#labelBox'), 'country', 'label');
fillIfUnique($('#countryBox'), $('#valueBox'), 'country', 'value');
}
});
};
setupAC();
});
Notes: I had to compress and insert XML into script. I removed duplicate entries in arrays.

How to select the check box on button click

In the users tab there are some rows having check boxes. So if more than 2 check boxes are selected then a button named group appears.
Now when group button is clicked then then it will ask for a name and after pressing the ok button on the right side in the group table a group is created. For example select 1st and last row and click the group button. A dialog box appears asking to enter name. Enter test in the input field, after that in the right side group table test appears(please see the screenshot).
Now my question: is if I click the test(group name) now then on the left side the checkboxes will be selected. So in my case 1st check box and last check box will be selected. Please tell me how to do this. This is the fiddle
The js codes are as follows
$(function() {
$("#datetimepicker").datetimepicker({
format: "'dd/MM/yyyy hh:mm:ss'",
linkField: "#txt",
linkFormat: "yyyy-mm-dd hh:ii",
autoclose: true,
});
jQuery('#datetimepicker').datetimepicker().on('changeDate', function(ev){
$(".darea1").val($( ".darea1" ).val()+$( "#txt" ).val());
});
});
$('#tabAll').click(function(){
$('#tabAll').addClass('active');
$('.tab-pane').each(function(i,t){
$('#myTabs li').removeClass('active');
$(this).addClass('active');
});
});
$('body').on('click', '.btn', function(){
if(this.id=='openAlert') {
$('#number').val('');}else{$('#number').val(this.id);
}
});
$(document).ready(function(){
$("#signout").click(function() {
window.location.replace("logout.jsp");
});
//next line
/*var val=0;
$(document).ready(function(){
$('#btn1').click(function(){
if($(".span4").val()!="")
{
$("#mytable").append('<tr id="mytr'+val+'"></tr>');
$("#mytr"+val).append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr'+val+'" checked ></td>');
$(".span4").each(function () {
$("#mytr"+val).append("<td >"+$(this).val()+"</td>");
});
val++;
}
else
{
alert("please fill the form completely");
}
});
$('#btn2').click(function(){
var creat_group=confirm("Do you want to creat a group??");
if(val>1){
alert(creat_group);
}
});
});*/
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var email=new Array();
var username=new Array();
var mobno=new Array();
var grpname;
var creat_group = prompt("Name your group??");
grpname=creat_group;
if (creat_group) {
console.log(obj);
$("#groupTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >" + creat_group + "</td>");
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
var arrid=0;
$(this).find('td').each(function() {
//your ajax call goes here
if(count == 1){
username[arrid]=$(this).html();
}
if(count==2)
{
email[arrid]=$(this).html();
}
if(count==3)
{
mobno[arrid]=$(this).html();
}
count++;
});
arrid++;
});
$.ajax(
{
type: "POST",
url: "messageSending.jsp", //Your full URL goes here
data: { username: username, email: email,mobno:mobno,grpname:grpname},
success: function(data, textStatus, jqXHR){
alert(data);
},
error: function(jqXHR){
alert(jqXHR.responseStatus);
}
});
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
//show group
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide')
}
else {
$('#btn2').addClass('hide')
}
//
});
});
//
$('#openAlert').click(function(){
var number = $('#number').val(); // If its a text input could use .text()
var msg = $('#darea').val(); //If its a text input could use .text()
alert(msg);
$.ajax(
{
type: "POST",
url: "messageSending.jsp", //Your full URL goes here
data: { toNumber: number, body: msg},
success: function(data, textStatus, jqXHR){
alert(data);
},
error: function(jqXHR){
alert(jqXHR.responseStatus);
}
});
});
});
$(function ()
{ $("#number").popover({title: 'Enter Mobile Number',content: "Please enter 10 digit mobile number prefixed by country code eg +911234567890"});
});
$(function ()
{ $("#body").popover({title: 'Message Body',content: "Maximum 160 characters allowed"});
});
Try this solution
add data-id for checkbox...set the value same as tr id or any
<tr id="46">
<td>
<input data-id="46" type="checkbox"></td>
<td>aaa</td>
jQuery
Add this lines in your code
var sCheckbox = new Array();
$('#mytable tr').find('input[type="checkbox"]:checked').each(function(i) {
sCheckbox.push($(this).attr("data-id"));
});
var ds = (sCheckbox.length > 0) ? sCheckbox.join(",") : "";
Modify this line
$tr.append("<td data-selected='"+ds+"'>" + creat_group + "</td>");
Add this event
$(document).on('click','#groupTable tr td',function () {
var dataids = $(this).attr("data-selected").split(",");
$('#mytable tr').find('input[type="checkbox"]').attr("checked",false);
$(dataids).each(function(key,dataid) {
$('#mytable tr').find('input[data-id="'+dataid+'"]').attr("checked",true);
})
});
Live Demo
Edit
Updated Demo
Add this data-id="mytr' + val + '" in checkbox element
$tr.append('<td class=\"cb\"><input data-id="mytr' + val + '" type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
note:check my inline comments in fiddle

Categories

Resources