This is my laravel view code. Here,I am trying to increment the counter value(ie.,value="0/5") . I have the input fields inside the modal and when clicking on the save button which is inside the model, the value should get incremented based on the filled input fields.ie(1/5..2/5..)
I have tried to increment those counter value.But it displays NaN
var val;
$("input").click(function() {
val = $('#counter').val();
val++;
$('#counter').prop('value', val)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none">
</div>
<script type="text/javascript">
$("input").click(function() {
let val = parseInt($('#counter').val().split('/')[0]);
$('#counter').prop('value', `${++val}/5`);
});
</script>
Actually your code is working fine. Since you have the view inside a modal, which is only displayed or shown on a click event, you should use the jQuery "on" method to enhance your click handler function definition. In that case you should have your code working
var val;
$(document).on('click','#counter',function()
{
val = $('#counter').val();
val++;
$('#counter').prop('value',val )
});
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i>
Price,stock and Shipping Information<input type="submit" id="counter"
**value="0/5"** style="background-color: transparent; border:none">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
You can use regular expression to parse data before / character
var val;
$("input").click(function() {
val = $('#counter').val();
qty = val.match(/[^/]*/i)[0];
qty++;
$('#counter').prop('value', qty)
});
If you want to increase like this 1/5..2/5 .Use split and increase only upper value .
var val;
$("input").click(function() {
val = $('#counter').val().split("/");
//check eqal value with base
if(val[0] == val[1]) {
return false;
}
val[0]++;
$('#counter').prop('value', val[0]+"/"+val[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none">
</div>
Here is your solution:
$("input").click(function() {
var val = $('#counter').val();
$('#counter').prop('value', `${++val % 6}/5`);
});
And a working fiddle:
https://jsfiddle.net/wv2x0mx5/4/
You can also try this.
$("#counter").on("click",function(){
var counterBtn = document.getElementById("counter");
var count = counterBtn.value;
//alert(count.split("/")[0]);
count = count.split("/");
counterBtn.value = ((parseInt(count[0])+1)%(parseInt(count[1])+1))+"/"+count[1];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-title pull-left">
<i class="fa fa-check-circle" style="font-size:20px;color:lightgreen">
</i> Price,stock and Shipping Information<input type="submit" id="counter" value="0/5" style="background-color: transparent; border:none">
</div>
Related
I want the user to be able to edit dynamically created list items that are input into a ul by the user.
I have no problem changing other items but the fact that the li items don't exist until input by the user is stumping me. I don't have any id's or classes to select to add a dblclick event to and selecting the child elements of all ul doesn't seem to work.
In short I just want to either:
click an icon on each list item that will allow me to edit the text
or
just double click the text which will allow me to edit it. (dblclick because the items are already draggable.)
I've tried a number of things but I'm not sure where to start now.
Thanks!
<div id="listWrapper" class="row">
<div id="dayInfo" class="container col-8">
<div class="card">
<img id="mondayImg" class="card-img-top">
<div class="card-body">
<h3 id="title" class="card-title">My Coding To-Do List</h3>
<div id="subTitle" class="row">
<div class="col">
<h5>Still to do</h5>
<button id="allFinished" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="stillToDo">
</ul>
<!-- <i class="fas fa-edit"></i> -->
</div>
<div class="col">
<h5>In Progress</h5>
<button id="allFinished2" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="inProgress">
</ul>
</div>
<div class="col">
<h5>Finished</h5>
<button id="removeFinished" class="btn btn-danger">Remove finished</button>
<hr>
<ul class="toBeSaved edit" id="finished">
</ul>
</div>
</div>
<div id="newItemWrapper">
<input id="newItem" placeholder="Add a new item">
<br>
<h6 id="newItemBtn" class="btn btn-primary">Add new item</h6>
<br>
<h6 id="save" class="btn btn-success">Save</h6>
<h6 id="clear" class="btn btn-warning">Clear</h6>
<p class="card-text"><small id="lastUpdated" class="text-muted toBeSaved">Last updated </small></p>
</div>
</div>
</div>
</div>
</div>
$(function() {
$("#newItem").focus();
//Adding a new items when click or enter pressed//
function addNewItem() {
let newInput = $("#newItem").val();
$("#stillToDo").append("<li>" + newInput + "</li>");
$("#newItem").val("");
$("#lastUpdated").text("Last updated " + Date());
};
$("#newItemBtn").click(addNewItem);
$("#newItem").keypress(function(e) {
if (event.which == 13) {
addNewItem();
}
});
//Moving list itmes and removing list items//
$("#allFinished").click(function() {
$("#finished").append($("#stillToDo li"))
});
$("#allFinished2").click(function() {
$("#finished").append($("#inProgress li"))
});
$("#removeFinished").click(function() {
$("#finished li").remove();
});
//So you can drag items across to another list
$("#stillToDo").sortable({
connectWith: "#finished, #inProgress"
});
$("#inProgress").sortable({
connectWith: "#finished, #stillToDo"
})
$("#finished").sortable({
connectWith: "#stillToDo, #inProgress"
});
//THIS IS SAVING LIST INFO and LAST UPDATED IN THE HTML 5 LOCAL STORAGE//
$(document).ready(function() {
$("#save").click(function(e) { //Clicking the "save button"//
e.preventDefault();
var everything = [];
$(".toBeSaved").each(function() {
everything.push(this.innerHTML);
})
localStorage.setItem('list', JSON.stringify(everything));
});
//RETREIVEING LISTS AND "UPDATED ON" FROM LOCAL STORAGE//
function loadEverything() {
if (localStorage.getItem('list')) {
var everything = JSON.parse(localStorage.getItem('list'));
$(".toBeSaved").each(function(i) {
this.innerHTML = everything[i];
})
}
}
loadEverything(); //<--This is calling the above function, without this nothing happens//
$("#clear").click(function(e) {
e.preventDefault();
localStorage.clear();
location.reload();
});
});
});
One simple way to edit text is to replace the text with an input element with it's value set to the text as follows:
//Edit added li elements
$(document).on('dblclick', 'ul.toBeSaved.edit li', function() {
let inEdit = $('<input/>');
let toEdit = $(this);
toEdit.html( inEdit.val( toEdit.text() ) );
inEdit.focus().select();
});
$(document).on('focusout keypress', 'ul.toBeSaved.edit li input', function(e) {
if( e.which === 13 || e.type === 'focusout') {
let val = $(this).val();
$(this).closest('li').text( val );
}
});
DEMO
$(function() {
$("#newItem").focus();
//Adding a new items when click or enter pressed//
function addNewItem() {
let newInput = $("#newItem").val();
$("#stillToDo").append("<li>" + newInput + "</li>");
$("#newItem").val("");
$("#lastUpdated").text("Last updated " + Date());
};
$("#newItemBtn").click(addNewItem);
$("#newItem").keypress(function(e) {
if (event.which == 13) {
addNewItem();
}
});
//End of adding a new items when click or enter pressed//
//Moving list itmes and removing list items//
$("#allFinished").click(function() {
$("#finished").append($("#stillToDo li"))
});
$("#allFinished2").click(function() {
$("#finished").append($("#inProgress li"))
});
$("#removeFinished").click(function() {
$("#finished li").remove();
});
//End of Moving list itmes and removing list items//
//So you can drag items across to another list
$("#stillToDo").sortable({
connectWith: "#finished, #inProgress"
});
$("#inProgress").sortable({
connectWith: "#finished, #stillToDo"
})
$("#finished").sortable({
connectWith: "#stillToDo, #inProgress"
});
//THIS IS SAVING LIST INFO and LAST UPDATED IN THE HTML 5 LOCAL STORAGE//
$(document).ready(function() {
$("#save").click(function(e) { //Clicking the "save button"//
e.preventDefault();
var everything = [];
$(".toBeSaved").each(function() {
everything.push(this.innerHTML);
})
localStorage.setItem('list', JSON.stringify(everything));
});
//\\END OF THIS IS SAVING LIST INFO and "UPDATED ON" IN THE BROWSER'S LOCAL STORAGE//
//RETREIVEING LISTS AND "UPDATED ON" FROM LOCAL STORAGE//
function loadEverything() {
if (localStorage.getItem('list')) {
var everything = JSON.parse(localStorage.getItem('list'));
$(".toBeSaved").each(function(i) {
this.innerHTML = everything[i];
})
}
}
loadEverything(); //<--This is calling the above function, without this nothing happens//
//END OF RETREIVEING LISTS AND "UPDATED ON" FROM LOCAL STORAGE//
$("#clear").click(function(e) {
e.preventDefault();
localStorage.clear();
location.reload();
});
});
//Edit added li elements
$(document).on('dblclick', 'ul.toBeSaved.edit li', function() {
let inEdit = $('<input/>');
let toEdit = $(this);
toEdit.html( inEdit.val( toEdit.text() ) );
inEdit.focus().select();
});
$(document).on('focusout keypress', 'ul.toBeSaved.edit li input', function(e) {
if( e.which === 13 || e.type === 'focusout') {
let val = $(this).val();
$(this).closest('li').text( val );
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sortable/0.9.13/jquery-sortable-min.js" integrity="sha512-9pm50HHbDIEyz2RV/g2tn1ZbBdiTlgV7FwcQhIhvykX6qbQitydd6rF19iLmOqmJVUYq90VL2HiIUHjUMQA5fw==" crossorigin="anonymous"></script>
<div id="listWrapper" class="row">
<div id="dayInfo" class="container col-8">
<div class="card">
<img id="mondayImg" class="card-img-top">
<div class="card-body">
<h3 id="title" class="card-title">My Coding To-Do List</h3>
<div id="subTitle" class="row">
<div class="col">
<h5>Still to do</h5>
<button id="allFinished" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="stillToDo">
</ul>
<!-- <i class="fas fa-edit"></i> -->
</div>
<div class="col">
<h5>In Progress</h5>
<button id="allFinished2" class="btn btn-success">Move all to finished</button>
<hr>
<ul class="toBeSaved edit" id="inProgress">
</ul>
</div>
<div class="col">
<h5>Finished</h5>
<button id="removeFinished" class="btn btn-danger">Remove finished</button>
<hr>
<ul class="toBeSaved edit" id="finished">
</ul>
</div>
</div>
<div id="newItemWrapper">
<input id="newItem" placeholder="Add a new item">
<br>
<h6 id="newItemBtn" class="btn btn-primary">Add new item</h6>
<br>
<h6 id="save" class="btn btn-success">Save</h6>
<h6 id="clear" class="btn btn-warning">Clear</h6>
<p class="card-text"><small id="lastUpdated" class="text-muted toBeSaved">Last updated </small></p>
</div>
</div>
</div>
</div>
</div>
I am trying to implement a dynamic increment/decrement counter. Here is how it should work:
I have an 'ADD' button. When i click on this, the same should disappear and a minus button, number input, plus button should appear. Clicking on "+" should increment the counter on the "cart" and clicking on "-" should decrement.
Below is html mycode
<body>
<div id="page-wrap">
<h1>Cart Inc Dec</h1>
<a href="#" class="btn btn-info btn-lg mt-5 mr-5 mb-5">
<span class="glyphicon glyphicon-shopping-cart"><span id="itemCount"></span></span> Check Out
</a>
<br>
<a id="btnAddItem" class="btn btn-primary float-right mt-5 mb-5 mr-5">ADD</a>
<div class="addItem">
</div>
</div>
</body>
Jquery:
<script>
var addElement = 0;
$(document).ready(function(){
$("#btnAddItem").on("click", function (event) {
if(addElement==0){
$(".addItem").append(('<button type="button" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" /><button type="button" class="counter increase">+</button>'));
}
addElement++;
});
var $input = $("#txtCounter");
// Initialise the value to 0
$input.val(0);
debugger;
// Increment/decrement count
$(".counter").click(function(){
console.log('here i am');
if ($(this).hasClass('increase'))
$input.val(parseInt($input.val())+1);
else if ($input.val()>=1)
$input.val(parseInt($input.val())-1);
});
});
</script>
Now the problem is after i add the dynamic +, text input counter, - controls, nothing happens when i click on + or minus. console.log inside $(".counter").click(function() is not giving anything.
Am i missing something??
You can do it like this: Adjust the $(".counter").click(function() {}); to $(document).on("click", ".counter", function(){}); as the element with the class counter isn't there when the page is initially loaded and therefore the click() event has to be delegated from a static parent element to the added counter element using on(). Move then the variable declaration var $input = $("#txtCounter"); inside this click function as the element with the id txtCounter isn't there when the page is initally loaded and move the initialization $("#txtCounter").val(0); after appending it.
var addElement = 0;
$(document).ready(function() {
$("#btnAddItem").on("click", function(event) {
if (addElement == 0) {
$(".addItem").append(('<button type="button" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" /><button type="button" class="counter increase">+</button>'));
// Initialise the value to 0
$("#txtCounter").val(0);
}
addElement++;
});
// Increment/decrement count
$(document).on("click", ".counter", function() {
var $input = $("#txtCounter");
if ($(this).hasClass('increase')) {
$input.val(parseInt($input.val()) + 1);
} else if ($input.val() >= 1) {
$input.val(parseInt($input.val()) - 1);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page-wrap">
<h1>Cart Inc Dec</h1>
<a href="#" class="btn btn-info btn-lg mt-5 mr-5 mb-5">
<span class="glyphicon glyphicon-shopping-cart"><span id="itemCount"></span></span> Check Out
</a>
<br>
<a id="btnAddItem" class="btn btn-primary float-right mt-5 mb-5 mr-5">ADD</a>
<div class="addItem">
</div>
</div>
You can change the script and try something like below:
var addElement = 0;
var myCounter= function(action){
var val = document.getElementById("txtCounter").value;
val = parseInt(val);
if(action == 2){ //Increase
document.getElementById("txtCounter").value=val+1;
}else if(val > 1){
document.getElementById("txtCounter").value=val-1;
}
};
$(document).ready(function(){
$("#btnAddItem").on("click", function (event) {
if(addElement==0){
$(".addItem").append(('<button type="button" onclick="myCounter(1);" class="counter decrease">-</button><input type="text" size="5" id="txtCounter" value="0" /><button type="button" onclick="myCounter(2);" class="counter increase">+</button>'));
}
addElement++;
});
});
I want to click on an item in the removeFood div and have it match to the item in the text area newFoodName1
$(".removeFood").click(function() {
var removedFood = ($(this).children('.dailyItem').text())
$(this).text('')
var selectedFood = $("#newFoodName1").text();
console.log(removedFood + selectedFood)
if (removedFood == selectedFood) {
console.log('They Match')
} else {
console.log('they dont match')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='removeFood'>
<p class='dailyItem'>
Eclair
<i class="fas fa-trash-alt"></i>
</p>
</div>
<textarea id='newFoodName1'>Eclair</textarea>
In the console this logs Eclair Eclair However the if statement says they do not match. What am I missing?
They do not match because of the whitespace around the values. If you use trim() to remove that, then the if condition is matched:
$(".removeFood").click(function() {
var removedFood = ($(this).children('.dailyItem').text())
$(this).text('')
var selectedFood = $("#newFoodName1").text();
console.log(removedFood + selectedFood)
if (removedFood.trim() == selectedFood.trim()) {
console.log('They Match')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='removeFood'>
<p class='dailyItem'>
Eclair
<i class="fas fa-trash-alt"></i>
</p>
</div>
<textarea id='newFoodName1'>Eclair</textarea>
just trim your data using trim()
$(".removeFood").click(function() {
var removedFood = ($(this).children('.dailyItem').text().trim())
$(this).text('')
var selectedFood = $("#newFoodName1").text().trim();
console.log(removedFood + selectedFood)
if (removedFood == selectedFood) {
console.log('They Match')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='removeFood'>
<p class='dailyItem'>
Eclair
<i class="fas fa-trash-alt"></i>
</p>
</div>
<textarea id='newFoodName1'>Eclair</textarea>
I can remove any item of array unless the last one. I also use angularjs to show information in the view. I don´t know what is happening with the last item of this array. Please, anyone can help me?
Here is HTML:
<div class="row">
<div class="col-md-12">
<h4><strong>Documento {{index + 1}} de {{documentos.length}}:</strong> {{documentos[index].nome}}</h4>
<iframe style="background: #ccc;" ng-show="exibirPreview" frameborder="0" ng-src="{{versaoLink}}" width="100%" height="300px"></iframe>
<div class="alert alert-warning" ng-hide="exibirPreview">
#Html.Raw(Resources.Dialog.SignDocuments.TypeDocumentCanNotPreDisplayed)
</div>
<hr />
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<button class="btn btn-default" type="button" ng-click="RemoveDoc(index)"><i class="fa fa-fw fa-times"></i> #Resources.Common.RemoveDocList</button>
</div>
</div>
</div>
Here is js/angularjs
$scope.documentos = [
{nome:"document1", chave: "8F65579E3737706F", extensao:".pdf"},
{nome:"document2", chave: "8F65579E3730007F", extensao:".pdf"},
{nome:"document3", chave: "8545579E3737706F", extensao:".pdf"},
{nome:"document4", chave: "8555579E3730007F", extensao:".pdf"}
]
$scope.ViewLink = function () {
var versao = $scope.documentos[$scope.index];
$scope.exibirPreview = versao.extensao == ".pdf" || versao.extensao == ".txt";
if (!$scope.exibirPreview) {
$scope.versaoLink = '';
} else {
$scope.versaoLink = '/Documento/VersaoView?chave=' + versao.chave;
}
};
$scope.ViewLink();
$scope.RemoveDoc = function (index) {
$scope.documentos.splice(index, 1);
$scope.ViewLink();
};
Or Plunker
In your HTML you are preventing the deletion of the last element:
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<!-- -->
</div>
documentos.length > 1 means "hide when it reaches one item in the array".
It should be documentos.length == 0.
It's either this or your index value starts from 1 and not from 0.
The simplest solution would be to change your remove function to take in the document instead of the index. Try this:
$scope.RemoveDoc = function(document) {
var index = $scope.documents.indexOf(document);
$scope.documents.splice(index, 1);
}
in view:
<button class="btn" type="button" ng-click="RemoveDoc(document)">Delete</button>
I have two div html elements with different id and here I am using spinner. Whenever values in the spinner input changes alert box will be displayed.
HTML code
<div id="accordion2" class="panel-group" style="display: block;">
<div id="accordion2" class="panel-group">
<div id="Tea">
<div class="spinner Tea input-group ">
<input type="text" id = "servings" class="form-control input- sm" value="Tea"/>
<div class="input-group-btn-vertical">
<button class="btn Tea btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Tea btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Tea"> Tea </h4>
</div>
<div id="Coffee">
<div class="spinner Coffee input-group ">
<input type="text" id = "servings" class="form-control input-sm" value="Coffee"/>
<div class="input-group-btn-vertical">
<button class="btn Coffee btn-default">
<i class="fa fa-caret-up"></i>
</button>
<button class="btn Coffee btn-default">
<i class="fa fa-caret-down"></i>
</button>
</div>
<h4 id="energy" class="Coffee">Coffee</h4>
</div>
</div>
</div>
JQuery code
$(function(){
$('.spinner:first-of-type input').on('click', function() {
$('.spinner:first-of-type input').val(parseInt($('.spinner:first-of-type input').val(), 10) + 1);
var val = $('.spinner:first-of-type input').val();
changeValues(val);
});
$('.spinner:last-of-type input').on('click', function() {
$('.spinner input').val( parseInt($('.spinner input').val(), 10) - 1);
});
function changeValues(value){
alert($('#energy').attr('class').split(' '));
};
});
But in the alert box whenever I click the spinner up arrow only Tea is displayed.
what I expect is when the spinner is clicked from Tea div tea should be displayed and when from coffee , coffee should be displayed.Please help me out
I'm not sure I totally got what you are trying to do, but it seems to me that you want to increment and decrement number of beverage cups on up/down buttons click. For this you would better modify mark up a little (remove duplicated ids, add classes for convenience). And I may look like this then:
$(function() {
$('.spinner').on('click', '.servings', function(e) {
$(this).val(parseInt($(this).val() || 0, 10) + 1);
var val = $(this).val();
changeValues.call(e.delegateTarget, val);
})
.on('click', '.up', function(e) {
$(e.delegateTarget).find('.servings').val(function() {
return ++this.value;
});
})
.on('click', '.down', function(e) {
var $input = $(e.delegateTarget).find('.servings');
if (+$input.val() > 1) {
$input.val(function() {
return --this.value;
});
}
});
function changeValues(value) {
var type = $(this).find('.energy').data('type');
alert(type);
};
});
Demo: http://plnkr.co/edit/9vXC0RipxkzqhXrHJAKD?p=preview
try this:
$(function () {
$('.spinner').each(function () {
var $el = $(this),
$buttons = $el.find('button'),
$h4 = $el.find('h4'),
input = $el.find('input').get(0);
function showAlert() {
alert($h4.get(0).className);
}
$buttons.eq(0).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) + 1;
showAlert();
});
$buttons.eq(1).on('click', function (event) {
event.preventDefault();
input.value = (parseInt(input.value, 10) || 0) - 1;
});
});
});
JSFiddle http://jsfiddle.net/yLtn57aw/2/
Hope this helps