How to stop adding duplicate values in select list box - javascript

I'm new to java script. I want prevent adding duplicate values to fourth list box. For example, It would not be same like below i) Paper Manufacturers << Paper Converters << Molded Pulp Products ii) Paper Manufacturers << Paper Converters << Molded Pulp Products And If there is no values in the fourth box, The "Remove Category" Button should be in disabled mode. If there is values & if i select any values in 4th box, The "Remove Category" Button should be enabled & "Add Category" button should be disabled.
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#tget");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count="";
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {alert('This category has already been added.');
return count=1;
}
else {
selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
return count=2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a=appendChoice();
if(a==2){
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>

Use this script. It will show alert if try to add duplicate entry. I have changed in function appendChoice().
$(document).ready(function () {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function () {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice() {
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function () {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function () {
removeCategoryButton.prop("disabled", false);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function () {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
});
}
});

Check the working code snippet
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton(){
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton );
}
function getNumberOfSelectedOption(){
return selectedList.find("option").length;
}
function getAvailableChoice(){
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice){
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice(){
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if(availableChoice >= 1){
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function(){
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener(){
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if(0 < availableChoice < 6){
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option>Paper Manufacturers</option>
<option>Paper Products Suppliers</option>
<option>Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option>Paper Converters</option>
<option>Lab Apparatus & Supplies</option>
<option>Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option>Molded Pulp Products</option>
<option>Software Vendors</option>
<option>Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>

Related

How do I add up all numbers into one variable and show it?

Whenever I try doing the code myself, nothing shows up after I run the function, I'm wanting to add all the numbers from 'fkWynik'.
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
document.getElementById('fkWynik').value = S.substr(2) + " = ";
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
You need to add the numbers together and concat it to the string:
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
var total = 0
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
total += I;
}
document.getElementById('fkWynik').value = S.substr(2) + " = "+total.toString();
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
The following should work if your HTML code contains an element with the property id="fkWynik"
function mat_WypiszLiczbyNaturalne() {
var elem = document.getElementById('fkEdit');
if(!elem) {
console.error("No element with id 'fkEdit' in the page.");
return;
}
var T = elem.value;
var value = "";
if (T && !isNaN(Number(T))) { // if T not null, not empty, not undefined, not 0 and is a number
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
value = S.substr(2) + " = ";
} else {
value = "Proszę wprowadzić liczbę!";
}
console.log("value: " + value);
document.getElementById('fkWynik').value = value;
}
mat_WypiszLiczbyNaturalne();

I cannot add the class "unread" to the append content of a certain data-id

I want to add the "unread" class to an append content with a specific data-id. The following line of code works fine in the browser console. However, when the code is run it does not add the class "unread".
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
The goal is to add "unread" in the following line of code:
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
I will provide you with a code snippet
<div id="conexion-chat">
<button id="btn-conexion-chat" onclick="initWebSocket();">Iniciar chat</button>
</div>
<div id="display-chat" style="display: none;">
<div id="visitors"></div>
<br />
<textarea id="chatRoomField" rows="10" cols="30" readonly></textarea> <br/>
<input id="sendField" value="" type="text">
<button id="sendButton" onclick="send_message();">Enviar</button>
</div>
function initWebSocket(){
$('#conexion-chat').css('display', 'none');
$('#display-chat').css('display', '');
websocket = new WebSocket("ws://localhost:8080/o/echo");
websocket.onopen = function (event) {
websocket.send(json_user());
};
websocket.onclose = function(event) {
localStorage.clear();
console.log("DESCONECTADO");
};
websocket.onmessage = function(event) {
var message = event.data;
processMessage(message);
};
websocket.onerror = function(event) {
console.log("ERROR: " + event.data);
};
}
function visitorSelected(event){
var visitorSelected = $(event.target).data('id');
localStorage.setItem('visitorSelected', visitorSelected);
websocket.send(json_messages(visitorSelected, '${email}', '${read}'));
document.getElementById("chatRoomField").innerHTML = "";
}
function processMessage(message){
if(message == '${disconnected}'){
document.getElementById("chatRoomField").innerHTML += "El patrocinador no se encuentra conectado." + "\n";
}else {
var json_message = JSON.parse(message);
var visitorSelected = localStorage.getItem('visitorSelected');
if(json_message.hasOwnProperty('message') && message.length > 0){
var message = json_message.message;
var text = "";
if('${currentUserRol}' != '${rolPreferences}'){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
if(message[message.length-1].id == visitorSelected || message[message.length-1].idTo == visitorSelected){
for(var i=0; i<message.length; i++){
text += message[i].from + ": " + message[i].message + "\n";
document.getElementById("chatRoomField").innerHTML = text;
}
}else{
var idMessage = message[message.length-1].id;
$('#visitors').find('h5[data-id=' + idMessage + ']').addClass('unread');
}
}
}
if(json_message.hasOwnProperty('visitors') && json_message.visitors.length > 0){
var visitors = json_message.visitors;
var state;
$("#visitors h5").remove();
for (var i = 0; i < visitors.length; i++) {
state = (visitors[i].idSession == visitorSelected)? "selected" : "not-selected";
$("#visitors").append('<h5 class="' + state + '" data-id=' + visitors[i].idSession + '>' + visitors[i].visitorOnline + '</h5>');
}
if(visitorSelected == null){
$("#visitors h5:first-child").attr("class", "selected");
visitorSelected = $("#visitors h5:first-child").attr("data-id");
localStorage.setItem('visitorSelected', visitorSelected);
}
}
}
}
$('#visitors').on('click', 'h5.not-selected', visitorSelected);
*Note: The entire code has not been submitted, but a code snippet.
Thanks!
Regards!

JavaScript class did not function in asp.net

I have created a javascript function in my aspx page..
below are the sample code,
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
</script>
I would like this function execute in the property such as
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>
As the code running, the javascript function above should be executed and display the " Choose Year" propery inside as shown above.
I try to run this code but nothing happens to the property. Any help would be appreciated. Thank u.
Your code seems to be working as below. However you may be missing the jQuery script so you can check if that exists.
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>

jquery .grep is not removing array element

$(document).ready(function () {
var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
$('#btn').click(function ()
{
var c = $("#ad_list option:selected").text();
numbers = jQuery.grep(numbers, function (value) {
return value != c;
}); >
});
var option = '';
for (i = 0; i < numbers.length; i++) {
option += '<option value="' + i + '">' + numbers[i] + '</option>'; >
}
$('#ad_list').append(option);
});
below is html code dropdownlist showing element in array
<label>ADD:</label>
<select name="ADD_list" id="ad_list"></select>
<input type="submit" id="btn" />
You need to update your option after removing the selected element:
function updateOption(numbers) {
$("#ad_list").empty();
var option = '';
for (i = 0; i < numbers.length; i++) {
option += '<option value="' + i + '">' + numbers[i] + '</option>';
}
$('#ad_list').append(option);
}
$(document).ready(function () {
var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
$('#btn').click(function () {
var c = $("#ad_list option:selected").text();
numbers = jQuery.grep(numbers, function (value) {
return value != c;
});
updateOption(numbers);
});
updateOption(numbers);
});
Fiddle Demo

Problems with creating dynamically <select/>

<script type="text/javascript">
var a = new Array();
function obj(type, value) {
this.type = type;
this.value = value;
this.toStr = toStr
}
function toStr() {
if (this.type == "select") {
var temp = "";
var arr = this.value.split("/");
for (i = 0; i < arr.length; i++) {
temp += "<option>" + arr[i] + "</option>"
}
return "<select>" + temp + "</select><br>";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "'><br>";
}
function addObj(type) {
var sel = parent.frames["left"].document.form1.q.value;
for (i = 0; i < sel; i++)
a[a.length] = new obj(type,
parent.frames["left"].document.form1.caption_text.value,
a.length);
paint();
parent.frames["left"].document.form1.caption_text.value = "";
}
function paint() {
parent.frames["right"].document.open()
for (i = 0; i < a.length; i++)
parent.frames["right"].document.writeln(a[i].toStr())
parent.frames["right"].document.close()
}
</script>
<form name=form1>
<table>
<tr>
<td><input type="button" style="width: 150px" value="Add Button" onClick="addObj('button')"><br />
<input type="button" style="width: 150px" value="Add TexBox" onClick="addObj('text')" /><br />
<input type="button" style="width: 150px" value="Add Select" onClick="addObj('select')" /></td>
<td>Text : <br /> Number of adding elements:<br /></td>
<td><input type="text" name="caption_text" style="width: 150px"> <br /> <select
NAME=q size=1 style="width: 150px">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
</tr>
</table>
</FORM>
Code is corrupting when creating select elements.
What's wrong with this code?
Thanks in advance.
Your i variables are missing a var declaration. All loops use the same counter, which means that nested loops will break horribly. My suggestion:
var a = [];
function FormElement(type, value) {
this.type = type;
this.value = value;
}
FormElement.prototype.toString = function toStr(){
if (this.type == "select") {
var arr = this.value.split("/");
for (var i = 0; i < arr.length; i++) {
arr[i] = "<option>" + arr[i] + "</option>"
}
return "<select>" + arr.join("") + "</select><br />";
} else
return "<input type = '" + this.type + "' value = '" + this.value + "' /><br />";
};
function addObj(type) {
var form = parent.frames["left"].document.form1;
var sel = form.q.value;
for (var i = 0; i < sel; i++)
a.push(new FormElement(type, form.caption_text.value);
paint();
form.caption_text.value = "";
}
function paint() {
var doc = parent.frames["right"].document;
doc.open();
doc.write(a.join("\n"));
doc.close();
}

Categories

Resources