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));
});
Related
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!
In my code below I am not able to trigger the quantity function. Normally, when I execute the quantity function below I use keyup, i.e when I start typing in the quantity box.
However this time, in the quantity input box below I fetch a value from the database into it already so on page load I am expecting the function trigger to run that function. That is not working. How can I get this done?
$(document).ready(function() {
#foreach($products - > items as $item)
var item = $('#{!! $item->id !!}');
var ad = JSON.parse(item.attr('data-item'));
if (item.prop("checked")) {
$('.panel').append(
'<div class="container"> ' +
'<p class="name" >' + ad.name + '</p>' +
'<p class="price" data-price="' + ad.price + '">' + ad.price + '</p>' +
'<p class="total" ><span class="line-total" name="total" id="total"></span></p>' +
'<input size="50" type="text" class="form-control quantity" placeholder=" qty " name="quantity[]" value="{!!$item->pivot->quantity!!}" required/>' +
'</div>'
)
} else {
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
}
quantityFunction();
#endforeach
update
<script>
var quantityFunction => function() {
var container = $(this).closest('div');
var sum;
var quantity = Number($(this).val());
var price = Number($(this).closest('div').find('.price').data('price'));
points = Number($(this).closest('div').find('.points').data('points'));
container.find(".total span").text(quantity * price);
container.find(".pts-total span").text(quantity * points);
sum = 0;
$(".line-total").each(function(){
sum = sum + Number($(this).text());
})
}
</script>
Why don't you put the quantity function into a non anonymous function and call it on document ready?
var quantityFunction = function() {
// your code here
}
and
$( document ).ready(function() {
quantityFunction ();
});
EDIT
JS Snipped:
var quantityFunction = function() {
var container = $(this).closest('div');
var sum;
var quantity = Number($(this).val());
var price = Number($(this).closest('div').find('.price').data('price'));
points = Number($(this).closest('div').find('.points').data('points'));
container.find(".total span").text(quantity * price);
container.find(".pts-total span").text(quantity * points);
sum = 0;
$(".line-total").each(function() {
sum = sum + Number($(this).text());
});
}
Doesn't it have to be here?
$('.panel').on('trigger','click',function() { }
$('.panel').on('trigger','.quantity',function()
Which event you want to trigger on the .panel?
Correct format for .on jQuery method is
.on( events [, selector ] [, data ], handler )
eg:
$('.panel').on('click','.quantity',function() {} );
Changes to your updated code,
var $container = $('.panel').closest('div');
var sum;
var quantity = Number($('.quantity').val());
var price = Number($container.find('.price').data('price'));
points = Number($container.find('.points').data('points'));
$container.find(".total span").text(quantity * price);
$container.find(".pts-total span").text(quantity * points);
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
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
}
So what I am trying to achieve is to increment the points".$id." in the javascript code below starting from 0 like points+n and it would be a dynamic value according to rows in a table. Same for the value 'button".$id."' and all this is because of styled radiobutton labels that are looped etc.
So all I want to do is get rid of all the hardcoded different var txt1 to txt+n, button0 to button+n and points0 to points+n in the JavaScript function.
The real problem here for me is the line: var buttons1 = document.forms[0].button0; how to replace the 0 in button0 to the 'i' in a for loop. Someting like button + i won't work.
Oh and what I'm trying to do is get the values from the radiobuttons to a textarea with one buttongroup and textarea per tablerow.
The code below works for the first 7 rows in my table...
echo "
<td>
<div class='radio'>
<input id='".$temp1."' type='radio' name='button".$id."' onclick='myFunction()' value='4'>
<label for='".$temp1."'></label>
<input id='".$temp2."' type='radio' name='button".$id."' onclick='myFunction()' value='3'>
<label for='".$temp2."'></label>
<input id='".$temp3."' type='radio' name='button".$id."' onclick='myFunction()' value='2'>
<label for='".$temp3."'></label>
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction()' value='1'>
<label for='".$temp4."'></label>
</div>";
echo"<textarea id='points".$id."' name='points".$id."' cols='1' rows='1' ;> </textarea>
</td>
</tr>";
The Javascript function:
function myFunction() {
var txt1 ='';
var txt2 ='';
var txt3 ='';
var txt4 ='';
var txt5 ='';
var txt6 ='';
var txt7 ='';
var buttons1 = document.forms[0].button0;
var buttons2 = document.forms[0].button1;
var buttons3 = document.forms[0].button2;
var buttons4 = document.forms[0].button3;
var buttons5 = document.forms[0].button4;
var buttons6 = document.forms[0].button5;
var buttons7 = document.forms[0].button6;
var buttons8 = document.forms[0].button7;
for (var i = 0; i < 4; i++) {
if (buttons1[i].checked) {
txt1 = txt1 + buttons1[i].value + " ";
}
if (buttons2[i].checked) {
txt2 = txt2 + buttons2[i].value + " ";
}
if (buttons3[i].checked) {
txt3 = txt3 + buttons3[i].value + " ";
}
if (buttons4[i].checked) {
txt4 = txt4 + buttons4[i].value + " ";
}
if (buttons5[i].checked) {
txt5 = txt5 + buttons5[i].value + " ";
}
if (buttons6[i].checked) {
txt6 = txt6 + buttons6[i].value + " ";
}
if (buttons7[i].checked) {
txt7 = txt7 + buttons7[i].value + " ";
}
}
document.getElementById("points0").value = txt1;
console.log(txt1);
document.getElementById("points1").value = txt2;
console.log(txt2);
document.getElementById("points2").value = txt3;
console.log(txt3);
document.getElementById("points3").value = txt4;
console.log(txt4);
document.getElementById("points4").value = txt5;
console.log(txt5);
document.getElementById("points5").value = txt6;
console.log(txt6);
document.getElementById("points6").value = txt7;
console.log(txt7);
}
i think what you need is use the "eval" function in javascript
try the following
var buttons1;
var buttons2;
var buttons3;
var buttons4;
var buttons5;
var buttons6;
var buttons7;
var buttons8;
var j;
for(var i=0;i<8;i++){
j=i+1;
eval("buttons" +j+ " = document.forms[0].button" +i+ ";");
}
If i understood correctly,
Try something like this:
change your onclick as following:
<input id='".$temp4."' type='radio' name='button".$id."' onclick='myFunction(this)' value='1'>
and change function :
function myFunction(button){
var name= button.name;
var id= name.split('button')[1];;
document.getElementById("points"+id).value = buttons.value +" ";
}