I have some code that adds items to a select list which works fine. However, what I need to do is compare a value that has already been entered so the user cannot enter dupe values. I know how to compare values but cannot get my head round how to check for value already entered.
I would be grateful if someone could shed some light on how to do this. Many thanks
js
$(function() {
$(document).on('click', '#add', function() {
var boxvalue = $("#box_input").val();
if (boxvalue == '') {
$("#niinputmessage").fadeIn(3000).html('No blank entries').fadeOut(5000).css({
'color': 'red',
'margin-left': '5px',
'margin-top': '5px'
});
return false;
}
count = $('#box_ni').children('option').length;
$("#counter").html("Total selected boxes for intake: " + '<span style="font-size: 14px; color: black;">' + '( ' + count + ' )' + '</span>').css('color:, black');
if (count > 2) {
$("#counter").html("No more than 3 items per intake. Please remove items from the list.");
return false;
} else {
count++;
$("#counter").html("Total selected boxes for intake: " + '<span style="font-size: 14px; color: black;">' + '( ' + count + ' )' + '</span>').css('color:, black');
}
$("#box_ni").append("<option>" + boxvalue + "</option>");
$("#box_input").val('');
});
});
js remove function
$(function() {
$(document).on('click', '#remove', function() {
$("#box_ni > option:selected").each(function() {
$("#box_ni option:selected").remove();
count--;
});
$("#counter").html("Total selected boxes for intake: " +
'<span style="font-size: 14px; color: black;">' + '( ' + count + ' )' +
'</span>').css('color:, black');
});
});
Checking for value can be done with a selector, but from your append script, you are not adding a value, but rather <option>value</option> (as opposed to with a value: <option value='value'>value</value>).
You can filter the results by checking the .text() of each option:
if ($("#box_ni option").filter(function (i,e) {
return $(e).text() == boxvalue ;
}).length > 0)
{
$("#counter").html("You've already selected that");
}
Snippet showing possible checks with value and text:
var newval = "1"
console.log("1", $("#sel option[value='"+newval+"']").length == 1)
var newval = "3"
console.log("3", $("#sel option[value='"+newval+"']").length == 1)
var newtext = "one"
console.log("one", $("#sel option").filter(function (i,e) { return $(e).text() == newtext; }).length == 1)
var newtext = "three"
console.log("three", $("#sel option").filter(function (i,e) { return $(e).text() == newtext; }).length == 1)
<select id='sel'>
<option value="1">one</option>
<option value="2">two</option>
</select>
add this in place of $("#box_ni").append....
var values = document.getElementsByTagName('option');
var j=0;
for(i=0; i < values.length; i++){
if(boxvalue == values[i].innerHTML){
j++;
}
}
if(j==0){
$("#box_ni").append("<option>" + boxvalue + "</option>");
}
You could try maintaining the list of values in an array and using that to represent the list's entries.
$(function() {
let boxvalues = [];
$(document).on('click', '#add', function() {
var boxvalue = $("#box_input").val();
if (boxvalue == '') {
$("#niinputmessage").fadeIn(3000).html('No blank entries').fadeOut(5000).css({
'color': 'red',
'margin-left': '5px',
'margin-top': '5px'
});
return false;
}
count = $('#box_ni').children('option').length;
$("#counter").html("Total selected boxes for intake: " + '<span style="font-size: 14px; color: black;">' + '( ' + count + ' )' + '</span>').css('color:, black');
if (count > 2) {
$("#counter").html("No more than 3 items per intake. Please remove items from the list.");
return false;
} else {
count++;
$("#counter").html("Total selected boxes for intake: " + '<span style="font-size: 14px; color: black;">' + '( ' + count + ' )' + '</span>').css('color:, black');
}
//Checks and adds the entries
if(boxvalues.indexOf(boxvalue) === -1) {
boxvalues.push(boxvalue)
$("#box_ni").append("<option>" + boxvalue + "</option>");
}
$("#box_input").val('');
});
});
Related
I want to show labels only if the facet has any options. Therefore I tried the following code:
<script>
(function($) {
$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ($('.facet-label[data-for="' + facet_name + '"]').length < 1 && $(this).children()
.length > 0) {
$(this).before('<p class="h5 facet-label" data-for="' + facet_name + '">' + facet_label + '</p>');
}
});
});
})(jQuery);
</script>
It works but only if I reload the page with active filters.
If I change the filter, the labels stay.
Is there any option to ask if the are a new filters after a click?
The plugin author gave me an hint for a solution:
<script>
(function($) {
$(document).on('facetwp-loaded', function() {
$('.facetwp-facet').each(function() {
var facet_name = $(this).attr('data-name');
var facet_label = FWP.settings.labels[facet_name];
if ( 'undefined' !== typeof FWP.settings.num_choices[facet_name] && FWP.settings.num_choices[facet_name] > 0 && $('.facet-label[data-for="' + facet_name + '"]').length < 1 ) {
$(this).before('<h3 class="facet-label" data-for="' + facet_name + '">' + facet_label + '</h3>');
} else if ( 'undefined' !== typeof FWP.settings.num_choices[facet_name] && !FWP.settings.num_choices[facet_name] > 0 ) {
$('.facet-label[data-for="' + facet_name + '"]').remove();
}
});
});
})(jQuery);
</script>
I have a table where the user can select row and they can edit in the header of the table. The problem is that, when they select row and changed the value; for example the Category. When first time edit the row and click the update, it will change accordingly. But when they select another value for Category or any other dropdown. They cannot changed it back from the previous value.
This is my code snippet, don't mind the background-color
var opt = $("#Category_h option:selected").val();
$('#' + dataTR).find('td[data-attr=Category]').find("#Category option[value='" + opt + "']").attr("selected", true);
if ($("#" + dataTR).find('td[data-attr=Category]').css('background-color') == 'rgb(255, 0, 0)') {
if (opt != '') {
$("#" + dataTR).find('td[data-attr=Category]').css('background-color', '');
}
}
Here's my whole code: Sample Code
Thanks
The problem with the code is you are using attr method which selects the options but you have not unselected it hence it stops working. You can use below modified code snippet to make things work.
$("input[name='Update']").click(function () {
if ($(this).attr("data-tr") == "-1") { return; };
var dataTR = $(this).attr("data-tr");
dataTR = dataTR.trim();
var customer_model;
var opt = $("#Category_h option:selected").val();
console.log(opt);
$('#' + dataTR).find('td[data-attr=Category]').find("#Category").val(opt);
if ($("#" + dataTR).find('td[data-attr=Category]').css('background-color') == 'rgb(255, 0, 0)') {
if (opt != '') {
$("#" + dataTR).find('td[data-attr=Category]').css('background-color', '');
}
}
var tax = $("#Tax_rule_h option:selected").val();
$('#' + dataTR).find('td[data-attr=Tax_rule]').find("#Tax_rule").val(tax);
if ($("#" + dataTR).find('td[data-attr=Tax_rule]').css('background-color') == 'rgb(255, 0, 0)') {
if (tax != '') {
$("#" + dataTR).find('td[data-attr=Tax_rule]').css('background-color', '');
}
}
var term = $("#Payment_term_h option:selected").val();
$('#' + dataTR).find('td[data-attr=Payment_term]').find("#Payment_term").val(term);
if ($("#" + dataTR).find('td[data-attr=Payment_term]').css('background-color') == 'rgb(255, 0, 0)') {
if (term != '') {
$("#" + dataTR).find('td[data-attr=Payment_term]').css('background-color', '');
}
}
//BTG v.1.0.0.3
var curr = $("#Currency_h option:selected").val();
$('#' + dataTR).find('td[data-attr=Currency]').find("#Currency").val(curr);
console.log(curr);
if ($("#" + dataTR).find('td[data-attr=Currency]').css('background-color') == 'rgb(255, 0, 0)') {
if (curr != '') {
$("#" + dataTR).find('td[data-attr=Currency]').css('background-color', '');
}
}
});
hope this will help you
Please take a look at the following jsfiddle.
https://jsfiddle.net/51Le6o06/42/
As you can see the table filter ('.filter-gift') populates itself with data from the HTML table below it. I have hidden all other scripts to make this easier to see.
The problem is when I select a filter for instance "Free TV" the corresponding table filters correctly, but if I then select the default filter option in the table the filter hides all rows.
Ideally selecting the default option "-Select-" should display all rows, how can I change my code so this is the case with my function.
jQuery/Javascript used:
$(document).ready(function() {
$('.filter-gift').each(filterItems);
});
function filterItems(e) {
var items = [];
var table = '';
tableId = $(this).parent().parent().attr('tag')
var listItems = "";
listItems += "<option value='0'> -Select- </option>";
$('div[tag="' + tableId + '"] table.internalActivities .information').each(function (i) {
var itm = $(this)[0].innerText;
if ($.inArray(itm, items) == -1) {
items.push($(this)[0].innerText);
listItems += "<option value='" + i + "'>" + $(this)[0].innerText + "</option>";
}
});
$('div[tag="' + tableId+ '"] .filter-gift').html(listItems);
$('.filter-gift').change(function () {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
});
}
set value to 999 > use if($(this).val()!= 999) else statement as below
$('.filter-gift').change(function () {
if($(this).val()!= 999) {
var tableIdC = $(this).parent().parent().attr('tag');
var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
$('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
$(this).show();
$(this).prev().show();
$(this).next().show();
}
else {
$(this).hide();
$(this).prev().hide();
$(this).next().hide();
}
});
} else {
$(this).parent().parent().find('table tr').show();
}
});
Please try the jsFiddle with jQuery UI selectmenu and 2 buttons.
With the help of 2 buttons prevGame and nextGame I am able to change the selectedIndex variable tracking the currently selected game number.
The jQuery UI selectmenu doc unfortunately does not explain how to set and get (so that I can update the span currGame) the currently selected item:
Please explain: how to set and get the selected item in jQuery UI selectmenu?
HTML-code:
<form>
<select name="games" id="games"></select>
<button id="prevGame"><</button>
<span id="currGame">Loading...</span>
<button id="nextGame">></button>
</form>
JavaScript-code:
var yourGames = [1, 3, 5];
var hisGames = [8, 10, 12, 14];
var selectedIndex = 0;
$("#games").selectmenu();
// emulate repeating server responses
setInterval(function() {
updateMenu();
}, 5000);
$('#prevGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
updateButtons();
});
$('#nextGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, lastIndex());
updateButtons();
});
function lastIndex() {
return yourGames.length + hisGames.length - 1;
}
function updateButtons() {
$('#currGame').html('selectedIndex=' + selectedIndex); // TODO: change to "Game #"
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
}
function updateMenu() {
var yourGroup = ['<optgroup label="YOUR TURN">'];
for (var i = 0; i < yourGames.length; i++) {
var gameNumber = yourGames[i];
var selectedTag = (i == selectedIndex ? 'selected="selected"' : '');
yourGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
yourGroup.push('</optgroup>');
var hisGroup = ['<optgroup label="HIS TURN">'];
for (var i = 0; i < hisGames.length; i++) {
var gameNumber = hisGames[i];
var selectedTag = (i - yourGames.length == selectedIndex ? 'selected="selected"' : '');
hisGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
hisGroup.push('</optgroup>');
$("#games").selectmenu('destroy')
.empty()
.append(yourGroup.length > 2 ? yourGroup.join('') : '')
.append(hisGroup.length > 2 ? hisGroup.join('') : '')
.selectmenu(); // TODO: select the game at selectIndex
}
UPDATE:
I have prepared a newer jsFiddle using selectmenu("refresh") instead of selectmenu("destroy"), but it still has some issues.
jQuery and jQuery UI provides no way to directly set selected index of a select menu. You can use pure javascript way to set the selected index. Also I assume you want to change the text between buttons every time select menu changes. You can do it like so:
var yourGames = [1, 3, 5];
var hisGames = [8, 10, 12, 14];
var selectedIndex = 0;
setInterval(function() {
updateMenu();
updateCurrentGame();
updateButtons();
}, 5000);
$("#games").selectmenu();
$('#prevGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
updateButtons();
updateCurrentGame();
});
$('#nextGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, lastIndex());
updateButtons();
updateCurrentGame();
});
function lastIndex() {
return yourGames.length + hisGames.length - 1;
}
function updateButtons() {
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
}
// Update the select menu when prev & next buttons are pressed
function updateCurrentGame() {
var selectedText = $($("select#games option")[selectedIndex]).text();
$('#currGame').html(selectedText);
// pure js vay to set selected index
$("#games")[0].selectedIndex = selectedIndex;
$("#games").selectmenu("refresh");
}
// Update the selected index every time the select menu is changed manually
$("#games").on("selectmenuchange", function(e, ui) {
console.log(ui);
selectedIndex = ui.item.index;
var selectedText = ui.item.element.text();
$('#currGame').html(selectedText);
updateButtons();
})
function updateMenu() {
var yourGroup = ['<optgroup label="YOUR TURN">'];
for (var i = 0; i < yourGames.length; i++) {
var gameNumber = yourGames[i];
var selectedTag = (i == selectedIndex ? 'selected="selected"' : '');
yourGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
yourGroup.push('</optgroup>');
var hisGroup = ['<optgroup label="HIS TURN">'];
for (var i = 0; i < hisGames.length; i++) {
var gameNumber = hisGames[i];
var selectedTag = (yourGames.length + i == selectedIndex ? 'selected="selected"' : '');
hisGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
hisGroup.push('</optgroup>');
$("#games").selectmenu('destroy')
.empty()
.append(yourGroup.length > 2 ? yourGroup.join('') : '')
.append(hisGroup.length > 2 ? hisGroup.join('') : '')
.selectmenu();
}
button#prevGame,
span#currGame,
button#nextGame,
button#newGame {
vertical-align: top;
}
select#games {
width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.min.css" rel="stylesheet" />
<form>
<select name="games" id="games"></select>
<button id="prevGame"><</button>
<span id="currGame">Loading...</span>
<button id="nextGame">></button>
</form>
This can be done in much better way but the following code provides what you asked for:
var yourGames = [1, 3, 5];
var hisGames = [8, 10, 12, 14];
var selectedIndex = 0;
$("#games").selectmenu();
$('#prevGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, 0);
updateMenu();
updateButtons();
});
$('#nextGame').button().click(function(e) {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, lastIndex());
updateMenu();
updateButtons();
});
function lastIndex() {
return yourGames.length + hisGames.length - 1;
}
function updateButtons() {
var selectedText = $("#games option:selected").text();
$('#currGame').html(selectedText);
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
}
function updateMenu() {
var yourGroup = ['<optgroup label="YOUR TURN">'];
for (var i = 0; i < yourGames.length; i++) {
var gameNumber = yourGames[i];
var selectedTag = (i == selectedIndex ? 'selected="selected"' : '');
yourGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
yourGroup.push('</optgroup>');
var hisGroup = ['<optgroup label="HIS TURN">'];
for (var i = 0; i < hisGames.length; i++) {
var gameNumber = hisGames[i];
var selectedTag = (yourGames.length + i == selectedIndex ? 'selected="selected"' : '');
hisGroup.push(
'<option ' +
selectedTag +
' value="' +
gameNumber +
'">Game #' +
gameNumber +
'</option>');
}
hisGroup.push('</optgroup>');
console.log(yourGroup);
console.log(hisGroup);
$("#games").selectmenu('destroy')
.empty()
.append(yourGroup.length > 2 ? yourGroup.join('') : '')
.append(hisGroup.length > 2 ? hisGroup.join('') : '')
.selectmenu();
}
I also updated your Fiddle so you can play with it.
https://jsfiddle.net/q07uarwr/35/
I gave it a try and got both updating and displaying text. But only thing you need to find next is how to set value once selected index changes to the next <option> group in the drop down.
This is the main change:
function updateButtons() {
var gamesOptions = $('#games option');
$('#currGame').html("<span>" + $(gamesOptions[selectedIndex]).text() + "</span>");
$("#games").val(selectedIndex).change();
$('#prevGame').button(selectedIndex == 0 ? "disable" : "enable");
$('#nextGame').button(selectedIndex == lastIndex() ? "disable" : "enable");
updateMenu();
}
https://jsfiddle.net/q07uarwr/34/
bus reservation
The following code generate multilpe <li> and when the user click seats, the selected seats css will change. but i want to restrict the multiple selection. the user has to be allow to select only one seat, if he select second <li> (seat) , then the first one has to go unselect
DEMO : http://demo.techbrij.com/780/seat-reservation-jquery-demo.php
CODE : http://techbrij.com/seat-reservation-with-jquery
$(function () {
var settings = {
rows: 6,
cols: 6,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 30,
seatHeight: 30,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1); // Seat No eg : seatNo = 0+0*0+1 (1)
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString(); // Class each seat class Name=seat row-0 col-0
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li onclick="gettable('+ seatNo+')" class="' + className +" table"+seatNo+ '">'
+'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
First remove the class from all elements, then add it to the selected one.
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
$('.' + settings.seatCss).removeClass(settings.selectingSeatCss);
$(this).addClass(settings.selectingSeatCss);
}
});
Change the else part to:
else{
$(this).toggleClass(settings.selectingSeatCss);
$(".settings.selectingSeatCss").not(this).removeClass('settings.selectingSeatCss');
}
try changing the code in click() event with this one.
$('.' + settings.seatCss).click(function () {
$(this).addClass(settings.selectedSeatCss).siblings(this).removeClass(settings.selectedSeatCss);
});
working Demo. Hope it helps you.