Jquery custom filters in HTML - javascript

I want create a custom filters using jquery.
I started here
var filters = {};
var data = [];
var filters = {};
filters.id = 0;
filters.title = "Users";
data[0] = filters;
var filters = {};
filters.id = 1;
filters.title = "Title";
data[1] = filters;
var filters = {};
filters.id = 2;
filters.title = "Start date";
data[2] = filters;
var filters = {};
filters.id = 3;
filters.title = "End date";
data[3] = filters;
var filters = {};
filters.id = 4;
filters.title = "Price";
data[4] = filters;
var filters = {};
filters.id = 5;
filters.title = "Category";
data[5] = filters;
var i = 0;
$.each(data, function(index, value) {
if (i < 2) {
$(".chooseFilter").append("<option data-filter-id=" + value.id + ">" + value.title + "</option>");
} else {
$(".chooseFilter").append("<option data-filter-id=" + value.id + " disabled>" + value.title + "</option>");
}
i++;
});
var dataHTMLFilters = [];
dataHTMLFilters[0] = '<input class="user" data-filterid="0" type="text" placeholder="Enter username">';
dataHTMLFilters[1] = '<input class="user" data-filterid="1" type="text" placeholder="Enter title">';
dataHTMLFilters[2] = '<input class="user" data-filterid="2" type="text" placeholder="Enter start date">';
dataHTMLFilters[3] = '<input class="user" data-filterid="3" type="text" placeholder="Enter end date">';
dataHTMLFilters[4] = '<input class="user" data-filterid="4" type="text" placeholder="Enter price">';
dataHTMLFilters[5] = '<input class="user" data-filterid="5" type="text" placeholder="Enter category">';
var limits = [];
limits[0] = 5;
limits[1] = 1;
limits[2] = 2;
limits[3] = 3;
limits[4] = 4;
limits[5] = 5;
$("body").on("change", ".chooseFilter", function() {
var filterId = $(this).find(":selected").attr("data-filter-id");
$(this).parent().prev().html(dataHTMLFilters[filterId]);
});
var buttons = '<div><button class="add">add</button><button class="remove">remove</button></div>';
$("body").on("click", ".add", function(e) {
e.preventDefault();
var filterID = $(this).parent().prev().find("option:selected").attr("data-filter-id");
$(".filters").append("<div class='filter'><div>" + $(".chooseFilter")[0].outerHTML + '</div>' + buttons + "</div>");
$(".filter").last().prepend("<div class='sibling'>" + dataHTMLFilters[$(".filter:last-child .chooseFilter option:not(:disabled)").attr("data-filter-id")] + "</div>");
if ($(".chooseFilter option[data-filter-id=" + filterID + "]:selected").length >= limits[filterID]) {
$(".chooseFilter option[data-filter-id=" + filterID + "]").prop("disabled", true);
var filterIdSelected = $(".chooseFilter option:not(:disabled)").first().attr("data-filter-id");
$(".chooseFilter").last().find("option[data-filter-id=" + filterIdSelected + "]").attr("selected", true);
console.log(dataHTMLFilters[filterIdSelected]);
$(".chooseFilter").last().parent().prev().html(dataHTMLFilters[filterIdSelected]);
}
});
$("body").on("click", ".remove", function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filters">
<div class="filter">
<div class="sibling">
<input class="user" data-filterid="0" type="text" placeholder="Enter username">
</div>
<div>
<select class="chooseFilter" style="width: 100%;">
</select>
</div>
<div>
<button class="add ">add</button>
</div>
</div>
</div>
Filters must fulfill,comatibile with:
Take limits to attention in add, remove and change. If limit is equal to instance of length in HTML document filter must be disabled
Basic filters are users, title when filters is only one this two option must be not disabled rest must be disabled when event is add, remove or change
Any ideas how I could do that? I try various method but result always are the same , filters is not compatibile.
If you want some more information how it should work just say.
I see it like this when add,remove and change:
if(users.length >= limit){
//set all option in select where filter is user to disabled = true
}
if(title.length >= limit){
//set all option in select where filter is title to disabled = true
}
if(filters.length > 1){
//options in select set to disable=false
}
if(filters.length < 1){
//options in select set to disable=true and title, users set to false
}

Related

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!

Dynamically assign ID and attach data in JavaScript & jQuery using two nested for loops

I am having some trouble to get through this below jsfiddle task.
jsfiddle link
I want to do the same function using dynamic id.
I tried so many methods, but nothing works.
Please don't recommend to change the infrastructure. The page has been already designed the same kind of structure.
I need to achieve this same kind of function using two nested for loops with dynamic id.
HTML:
<div class="col-md-4" id="beforeDiv0">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId0" value="1000" />
</div>
</div>
<br/><br/>
<div class="col-md-4" id="beforeDiv1">
<div class="col-md-2" style="padding-right: 0px; padding-top: 5px;">
<label for="Amount" style="font-weight:bold;">Amount:</label>
</div>
<div class="col-md-6">
<input class="form-control" type="number" id="textboxId1" value="1000" />
</div>
</div>
Javascript & jQuery:
$(document).ready(function(){
var newAmount = parseFloat(1000) + parseFloat(5);
for(var id=0; id<3; id++){
for (var i = 1; i < 3; i++) {
var html = '<tr style="height:50px;">';
html = html + '<td class="td-Amount" style="text-align: right; font-size: 15px; font-weight: bold;">';
html = html + 'Original: '+ '<span id="OrginalAmount' + i + '">' + 1000 + '</span><br/>' + 'New: <span id="Output' + id + "" + i + '">' + newAmount + '</span></td>';
html = html + '</tr>';
$(html).insertAfter("#beforeDiv" + id);
//var abc = id + "" + i;
//var xyz = '#textboxId' + id;
//var zyx = "Output"+id+""+i;
}
}
var myArr = new Array();
var myArr2 = new Array();
for(var id=0; id<3; id++){
var xyz = '#textboxId' + id;
myArr[id] = id;
for (var i = 1; i < 3; i++) {
myArr2[i] = i;
var calc = myArr[id] + "" + myArr2[i];
var zyx = "Output" + calc;
//below line is for dynamic id retrieval
/*
$(xyz).on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById(zyx).innerHTML = AmtChange;
});
*/
$("#textboxId0").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output01").innerHTML = AmtChange;
document.getElementById("Output02").innerHTML = AmtChange;
});
$("#textboxId1").on("click change paste keyup", function() {
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
document.getElementById("Output11").innerHTML = AmtChange;
document.getElementById("Output12").innerHTML = AmtChange;
});
}
}
});
I looked at your code, and considered your comments, and if I understand you correctly, then something like this is what you are after:
$('input[id^=textboxId]').on("click change paste keyup", function() {
var id = $(this).attr('id');
id = id.replace(/\D/g,'');
var x = parseFloat(1000);
var y = parseFloat($(this).val());
var AmtChange = x + y;
/**
* The following could not really be simplified, because
* there are no defining data- attributes, or anything
* to identify the table rows as belonging to the textbox.
* When I tried to simplify the selection of "output" spans,
* a span with id Output111 would have been matched by Output11
* and Output1.
*/
$('#beforeDiv' + id).nextUntil('br').each(function(i,el){
$('span[id^=Output]', this).text(AmtChange);
});
});
I tested this on Codepen: https://codepen.io/skunkbad/pen/ayeVLp

Jquery insert values of text-field into list-box.?

I want to fetch value from the textfield and add to the listbox.
Here is my jquery code
JS:-
{
$('#btn_AddToList').click(function(
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if('' != region)
{
var newOption = document.createElement('option');
newOption.text = region;
newOption.value = region;
if($.browser.msie)
{
select.add(newOption);
}
else
{
select.add(newOption, null);
}
}
return false;
});
});
here is my html code
html:
<input type="text" name="region" id="txt_RegionName" /><br />
<input type="button" name="add" id="btn_AddToList" value="add" class="btn btn-success" /></br />
<select size="10" id="lst_Regions" style="width: 500px;">
</select>
question: I cannot add the value of the txt_RegionName to the lst_Region ,where i am going wrong?
Thank you.
$('#btn_AddToList').click(function () {
var val = $('#txt_RegionName').val();
$('#lst_Regions').append('<option>' + val + '</option>');
$('#txt_RegionName').val('').focus();
})
jsFiddle example
you can do this like:
$('#btn_AddToList').click(function(event)
{
var region = $('#txt_RegionName').val();
if(region && !$('#lst_Regions>option[value=' + region + ']').length){
var newOption = $('<option value="' + region + '">' + region + '</option>');
$('#lst_Regions').append(newOption);
}
//return false;
event.preventDefault();
event.stopPropagation();
});
just to let you know, you can prevent it from duplicate values using:
$('#lst_Regions>option[value=' + region + ']').length
which has to be zero, and as you see I have added that to my answer.
{
$('#btn_AddToList').click(function()
{
var select = document.getElementById('lst_Regions');
var region = $('#txt_RegionName').val();
if ('' != region) {
$(document.createElement('option')).text(region).val(region).appendTo(select);
}
return false;
});
};

javascript value does not add up

I try to make a count up function whenever there is pressed on a button (button is not in this code).
the result of the count up should be in the read only text field.
var html='';
var huidig = 0;
$('body').off('click', '[data-type=product]').on('click', '[data-type=product]', function(e)
{
e.preventDefault();
var price = $(this).attr('data-price');
var name = $(this).attr('data-name');
var id = $(this).attr('data-id');
if($('input[value='+id+']').length > 0)
{
var parent = $('input[value='+id+']').parent();
console.log("parent: " + parent);
var currentValue = parseFloat(parent.find('input[name^=product_amount]').val());
console.log("currentValue: " + currentValue);
currentValue++;
console.log("currentValue: " + currentValue);
parent.find('input[name^=product_amount]').val(parseFloat(currentValue));
console.log(parent.find('input[name^=product_amount]').val(parseFloat(currentValue)));
}
else
{
html+='<div class="row-fluid"><div class="span1"><input type="hidden" name="product[]" value="'+id+'"/><input type="text" readonly="readonly" name="product_amount[]" value="0" /></div> <div class="span7">'+name+'</div> <div class="span3 offset1">€'+price+'</div> </div>';
}
$('.bill').html(html);
amount = amount + parseFloat(price);
$('.total_bill').html(amount.toFixed(2));
});

Remove options from select box if it is already selected in onother

I have a form. The user clicks the add button to add another state + text box for that state. When people select a state in the first box, I want it removed from any other select box that may be added so it can not be selected again.
<form action=state.php method=post>
<a href="javascript:addElement();" style='color:blue; text-decoration:underline;'>Add a State </a>
<a href='javascript:removeElement();' style='color:blue; text-decoration:underline;' >Remove </a><br /><br />
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement() {
intTextBox = intTextBox + 1;
var contentID = document.getElementById('addresscontent');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "<select id='u" + intTextBox + "' name=b_state[" + intTextBox + "][statename]/><option value=''>Select a State</option><option value='AK'>AK</option><option value='AL'>AL</option><option value='AR'>AR</option><option value='AS'>AS</option><option value='AZ'>AZ</option><option value='CA'>CA</option></select> <span style='font-size:12px;'>URL (if different) </span><input style='border:1px solid black; ' size=60 type='text' id='u" + intTextBox + "' name=b__state[" +intTextBox + "][url] /><br>";
contentID.appendChild(newTBDiv);
}
//FUNCTION TO REMOVE TEXT BOX ELEMENT
function removeElement() {
if(intTextBox != 0) {
var contentID = document.getElementById('addresscontent');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
</script>
<div id="addresscontent"></div>
</div>
<input type=submit value='go'>
Here are the steps you need:
1) Gather all of the relevant select fields into a node list:
document.getElementById("myBigForm").getElementsByTagName("select");
2) Now you need to loop through these select fields. For each select field you need to loop through the option elements
3) Perform a remove child if the option contains a certain value.
var removeState = function (x) {
"use strict";
var a = document.getElementById("myBigForm").getElementsByTagName("select"),
b = a.length,
c = 0,
d = [],
e = 0,
f = 0;
for (c = 0; c < b; c += 1) {
d = a[b].getElementsByTagName("option");
e = d.length;
for (f = 0; f < e; f += 1) {
if (d[f].value === x) {
a[b].removeChild(d[f]);
break;
}
}
}
};

Categories

Resources