I have a web page with JQuery which reads a json file and display tags on the webpage and also provide user a possibility to add the tags manually.
Below is the java script:
$(document).ready(function() {
setInterval(function, 2000);
$.getJSON('https://api.myjson.com/bins/1058x', function(res){
$.each(res.data, function(key, val){
$("<span class='tag label label-info'><span>"+val.tag+"</span><span class='glyphicon glyphicon-remove-sign'></span></span>").appendTo('.list')
});
});
$('#addButton').click(function() {
var toAdd=$('input[name=checkbox]').val();
var tag = "<span class='tag label label-info'><span>"+toAdd+"</span><span class='glyphicon glyphicon-remove-sign'></span></span>"
$(tag).appendTo('.list');
});
$('.list').on('click','span',function() {
$(this).parent().remove();
});
});
And below is the HTML Code:
<div class="jumbotron" style="border: 1px solid">
<h2 class="text-center">Tag suggestions:</h2>
<div class="row">
<p><br></p>
<div class="col-md-3 col-lg-3 text-center">
Refresh Rate:
</div>
<div class="col-md-7 col-lg-7 pull-left">
<input type="range" min="0" max="60" step="1" value="30" style="width:85%" onchange="updateTextInput(this.value);" />
</div>
<div class="col-md-2 col-lg-2 pull-left">
<input class="text-center" id="rangeValue" type="text" value="30" style="width:25%;border:2px solid #456879; border-radius:4px;" /> Minutes
</div>
</div>
<br><br>
<div class="text-center">
<div class="list">
</div>
</div>
<br><br>
<div class="text-center">
<form id="tagInput">
<input type='text' name='checkbox' style="border:2px solid #456879; border-radius:10px; height: 26px; width: 230px;"/>
</form>
<br><br>
<button id="addButton" class="btn btn-primary">Add New</button>
</div>
</div>
</div> <!-- /container -->
I have also created a jsFiddle here.
What I want now to refresh the javascript every two minutes. so that it can read the file every two minutes and display tags again without reloading the page again and again but just the tags. I would highly appriciate the help.
Thank you.
This should work.
window.setInterval(function(){
/// call your function here
}, 120000);
I updated your script:
var load = function () {
$.getJSON('https://api.myjson.com/bins/4skih', function (res) {
$.each(res.data, function (key, val) {
addTag(val.tag, key);
});
});
};
var init = function () {
load();
$('#addButton').on('click', function () {
var $input = $('input[name=checkbox]');
var toAdd = $.trim($input.val());
if (toAdd !== '') { // check value.
addTag(toAdd);
$input.val(''); //clear input after add.
}
});
$('.list').on('click', 'button', function () {
$(this).parent().remove();
});
setInterval(load, 2000 * 60); // Loading data each 2 min.
};
$(document).ready(init);
// Add tag to html.
var addTag = function (tag) {
$("<div><button class='tag'>" + tag + "</button></div>").appendTo('.list');
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-center">
<div class="list">
</div>
</div>
<br><br>
<div class="text-center">
<input type='text' name='checkbox' />
<br><br>
<button id="addButton" class="btn btn-primary">Add New</button>
</div>
If you would like to fetch data periodically, I guess you wanted to do this:
$(document).ready(function () {
setInterval(function () {
$.getJSON('https://api.myjson.com/bins/1058x', function (res) {
$.each(res.data, function (key, val) {
$("<span class='tag label label-info'><span>" + val.tag + "</span><span class='glyphicon glyphicon-remove-sign'></span></span>").appendTo('.list')
});
}, 1000 * 120);
});
});
As soon as document is ready, you invoke function every 2 minutes.
Related
I am doing calculation with function ("update_total") by "onchange" event of input tab number.
it is working fine. no any issue.
when i am using jquery plugin "Nice-Number" for showing plus(+), minus(-) button.
(https://www.jqueryscript.net/form/Number-Input-Spinner-jQuery-Nice-Number.html)
onchange event of input tag is not getting fire. because mouse get clicked on plus(+) or minus(-) button.
therefor i am not getting ("update_total") total value.
please help how to resolve this issue.
$(function() {
$('input[type="number"]').niceNumber();
});
function update_total(spineerid, product_price, totalid) {
spineerid = '#' + spineerid;
totalid = '#' + totalid;
var qty_count = $(spineerid).val();
var total = product_price * qty_count;
$(totalid).html(total + '/-'); // display total
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery.nice-number#2.1.0/src/jquery.nice-number.css" />
<script src="https://cdn.jsdelivr.net/npm/jquery.nice-number#2.1.0/src/jquery.nice-number.js"></script>
<div class="card" style="width:12rem">
<div class="card-header">
<?php echo $row['product_name'] ?>
</div>
<img src="product-images/<?php echo $row['product_image']; ?>" class="card-img-top" alt="..." height="150px">
<div>
<span> ₹<?php echo$row['product_price']?> </span>
</div>
<div>
<input type="number" min="1" value="1" name="spinnerNumber<?php echo $row['product_id']?>" id="spinnerNumber<?php echo $row['product_id']?>" onchange="update_total('spinnerNumber<?php echo $row['product_id']?>','<?php echo$row['product_price']?>','total<?php echo $row['product_id']?>')">
</div>
<div class="card-footer">
<!-- Total -->
<div>
Total: ₹ <span id="total<?php echo $row['product_id']?>">0</span>
</div>
</div>
</div>
just change:
onchange="update_total...
by oninput
oninput="update_total...
$('input[type="number"]').niceNumber();
function update_total(spineerid, product_price, totalid) {
spineerid = '#' + spineerid;
totalid = '#' + totalid;
var qty_count = $(spineerid).val();
var total = product_price * qty_count;
$(totalid).html(total + '/-'); // display total
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery.nice-number#2.1.0/src/jquery.nice-number.css" />
<script src="https://cdn.jsdelivr.net/npm/jquery.nice-number#2.1.0/src/jquery.nice-number.js"></script>
<div class="card" style="width:12rem">
<div class="card-header">Product1</div>
<img src="product-images/image1" class="card-img-top" alt="..." height="150px">
<div>
<span>100</span>
</div>
<div>
<input type="number" min="0" value="0" name="spinnerNumberProduct1"
id="spinnerNumberProduct1"
oninput="update_total('spinnerNumberProduct1','100','totalProduct1')">
</div>
<div class="card-footer">
<!-- Total -->
<div>
Total: <span id="totalProduct1">0</span>
</div>
</div>
</div>
i have just changed min="0" and value="0" to have a correct initialization
You need to make following two changes:-
Attach data attributes to the input fields so that you can access the values in the callbacks.
You need to pass the onDecrement & onIncrement callbacks in niceNumber()
Please find the changes below:-
`
<input
data-productid="<?php echo $row['product_id']?>"
data-productprice="<?php echo$row['product_price']?>"
type="number" min="1" value="1" name="spinnerNumber<?php echo $row['product_id']?>"
id="spinnerNumber<?php echo $row['product_id']?>">
`
`
<script>
$(function() {
$('input[type="number"]').niceNumber({
onDecrement: function ($currentInput, amount, settings) {
// Extract out data attributes from $currentInput
// Do your required calculations
},
onIncrement: function ($currentInput, amount, settings) {
// Extract out data attributes from $currentInput
// Do your required calculations
}
});
});
</script>
`
I have a form with some fields and after submit finish i want to reset whole form but only reset input text areas not input type file.
I check every similar questions and solutions but none of them work for me.Some solutions refresh page which i don't want that.
<form class=" dropzone px-5" id="mydropzone">
<h2 class="text-center">Lets create your menu</h2>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCalories">Calorie</label>
<input type="text" class="form-control" id="inputCalories" required>
</div>
<div class="form-group col-md-6">
<label for="cc">Calorie Calculator</label>
<button id="cc" class="btn btn-primary btn-lg"><i class="fas fa-calculator mr-2"></i>Click Me</button>
</div>
</div>
<div class="form-row">
<div class="form-group ml-2 col-sm-6">
<label>Menu Item Image</label>
<div id="msg"></div>
<div class="progress" id="uploader">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100" style="width: 10%"></div>
</div>
<input type="file" name="img[]" class="file" accept="image/*" id="fileButton">
<div class="input-group my-3">
<input type="text" class="form-control" disabled placeholder="Upload File" id="file" required>
<div class="input-group-append">
<button type="button" class="browse btn btn-primary"><i class="fas fa-folder-open mr-2"></i>Browse...</button>
</div>
</div>
<div class="ml-2 col-sm-6">
<img src=" " id="preview" class="img-thumbnail">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block mb-3">Submit Menu</button>
<!-- -------------------------------------------------------------------------- -->
</div>
</form>
And my create menu which clear all fields after form submit.
// create menu
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
fileButton.addEventListener('change', function(e) {
var file = e.target.files[0];
var storageRef = firebase.storage().ref('foodImg/' + file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function(error) {
console.error(error);
}, function() {
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
const createMenuForm = document.querySelector('#mydropzone');
createMenuForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('restaurants').add({
foodLine: {
menuTitle: createMenuForm.menuTitle.value
},
food: {
foodName: createMenuForm.foodName.value,
imageURL: downloadURL,
inputCalories: createMenuForm.inputCalories.value,
menuItemDescription: createMenuForm.menuItemDescription.value,
menuItemInfo: createMenuForm.menuItemInfo.value
}
}).then(() => {
//reset form
createMenuForm.reset();
fileButton.value = "";
var preview = document.getElementById('preview');
preview.value = "";
}).catch(err => {
console.log(err.message);
});
});
});
});
});
Can you try these things also
document.getElementById("myForm").reset();
$("#myForm").trigger("reset");
I think you try to access createMenuForm outside the scope where const createMenuForm was declared.
Try to declare it above the event listener:
// create menu
const createMenuForm = document.querySelector('#mydropzone');
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// ...
or directly with
document.querySelector('#mydropzone').reset();
i debug and find that preview need to be clean
document.getElementById("preview").src = "#";
I'm creating a plugin for Input Files, I created everything but without having in mind the possibility of having multiple inputs on screen, then it was necessary instead to manipulate the element from the element ID. This is so that actions in one input do not affect all other inputs on the screen.
Below is the code so far, I could not make it work when informed by the element ID.
function bs_input_file() {
// TODO: add function to hide remove button when file not informed
const inputElement = $(".input-file").find('input');
const inputId = inputElement.map(function (index, dom) {
return dom.id
});
buttonInspec(inputId);
function buttonInspec(id) {
$("#" + id).find("button.btn-reset").addClass("hidden");
var element = $("#" + id).find('input');
element.on("change input propertychange", function() {
console.log("changed!")
if (element.val() != "") {
$("#" + id).find("button.btn-reset").removeClass("hidden");
}
});
}
// Necessary to put ID below also
$(".input-file").before(
function() {
if (!$(this).prev().hasClass('input-ghost')) {
var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
element.attr("name", $(this).attr("name"));
element.change(function() {
element.next(element).find('input').val((element.val()).split('\\').pop());
});
$(this).find("button.btn-choose").click(function() {
element.click();
});
$(this).find("button.btn-reset").click(function() {
element.val(null);
$(this).parents(".input-file").find('input').val('');
});
$(this).find('input').css("cursor", "pointer");
$(this).find('input').mousedown(function() {
$(this).parents('.input-file').prev().click();
return false;
});
return element;
}
}
);
}
bs_input_file();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<h3>Example</h3>
<form method="POST" action="#" enctype="multipart/form-data">
<!-- COMPONENT START -->
<div class="form-group">
<div class="input-group input-file" name="Fichier1">
<input id="fileInput0" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group input-file" name="Fichier2">
<input id="fileInput1" type="text" class="form-control" placeholder='Select file...' />
<span class="input-group-btn">
<button class="btn btn-secondary btn-reset" type="button"><em class="glyphicon glyphicon-trash"></em></button>
<button class="btn btn-default btn-choose " type="button"><em class="glyphicon glyphicon-folder-open"></em> Search...</button>
</span>
</div>
</div>
<!-- COMPONENT END -->
</form>
</div>
</div>
I am trying to get .sortable from jQuery UI to work but it is only working for my first item, when I dynamically add new ones, it stops working.
I found this: http://api.jqueryui.com/sortable/#method-refresh which should refresh everything and recognize new items, but when I use that I get the error:
Uncaught Error: cannot call methods on sortable prior to initialization; attempted to call method 'refresh'
What can I do?
My code:
// HTML template for new fields
const template = `<div class="row sortwrap">
<div class="col-md-8">
<input type="text" name="category[]" placeholder="" class="form-control name_list catinput" />
<i class="mdi mdi-sort dragndrop"></i>
<div class="questionlist">
<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-success questionbutton">Extra vraag</button>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<button id="addcategory" class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
const vraagTemplate = `<div class="row">
<div class="col-md-8">
<input type="text" name="question[]" class="form-control name_list questioninput" />
</div>
<div class="col-md-4">
<button class="btn btn-danger btn_remove">X</button>
</div>
</div>`;
$('.sortwrap').sortable();
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
$('.sortwrap').sortable("refresh");
$('#dynamic_field input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
$('#dynamic_field .sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
$('#dynamic_field .questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append category template
$('#addcategory').click(function() {
$('#dynamic_field').append($(template));
updatePlaceholders();
});
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
$ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
If I remove the line that says refresh in my function and only have the one .sortable in my code then I can drag all items even new ones but nothing is dropping. So I can drag but not sort/drop.
I think this is on where you attach your sort. I used a wrapper here to do so.
Note I turned off the refresh due to where I attached it as it seems to not need that given that attachment point.
// HTML template for new fields
const template = '<div class="row sortwrap"> <div class="col-md-8"> <input type="text" name="category[]" placeholder="" class="form-control name_list catinput" /> <i class="mdi mdi-sort dragndrop"></i> <div class="questionlist"> <div class="row"> <div class="col-md-8"> <input type="text" name="question[]" placeholder="1. Voeg een vraag toe" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-success questionbutton">Extra vraag</button> </div> </div> </div> </div> <div class="col-md-4"> <button id="addcategory" class="btn btn-danger btn_remove">X</button> </div> </div>';
const vraagTemplate = '<div class="row"> <div class="col-md-8"> <input type="text" name="question[]" class="form-control name_list questioninput" /> </div> <div class="col-md-4"> <button class="btn btn-danger btn_remove">X</button> </div> </div>';
// Count numbers and change accordingly when field is deleted
function updatePlaceholders() {
// Sortable code
// $('#dynamic_field').sortable( "refresh" );
let df = $('#dynamic_field');
df.find('input[name^=cat]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een categorie toe");
});
df.find('.sortwrap').each(function(i) {
$(this).attr("id", i + 1);
});
df.find('.questionlist').each(function() {
$(this).find('input[name^=qu]').each(function(i) {
$(this).attr("placeholder", i + 1 + ". Voeg een vraag toe");
});
});
}
// Append question template
$('#dynamic_field').on('click', '.questionbutton', function() {
let $ql = $(this).closest('.questionlist');
$ql.append($(vraagTemplate));
updatePlaceholders();
});
// Delete
$('#dynamic_field').on('click', '.btn_remove', function() {
$(this).closest('.row').remove();
updatePlaceholders();
});
$('#addcategory').on('click', function() {
let t = $(template)
$('#dynamic_field').append(t);
updatePlaceholders();
});
$(function() {
$('#addcategory').trigger('click');
$('#dynamic_field').sortable();
});
.sortwrap{border: solid green 1px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<button id="addcategory">add</button>
</div>
<div id="dynamic_field"></div>
As mentioned above this will work fine
This looks promising:
http://api.jqueryui.com/sortable/#method-refresh
it seems to imply that you can just add an item to a sortable, then call
$('#mysortable').sortable('refresh')
to recognize it.
var counter = 1;
function appendThing() {
$("<li id='Text" + counter + "' class='ui-state-default'>Text" + counter + "</li>").appendTo($("#mySortable"));
$("#mySortable").sortable({ refresh: mySortable })
counter++;
};
please take a look into this
https://jsfiddle.net/6ztrdg9n/
I have a textarea and a textcounter. requirement is when i write something on the textarea the textcount should increase or decrease as per the text.But its not happening.The Code is Shown Below.
<div style="clear:both;"></div>
<div class="form-group col-md-12">
<div id="div_Description" name="div_Description" >
<div class="form-group col-md-12" style="padding-left:0px;">
<label>Description</label>
<?php
echo ('<textarea class="form-control" counter_box="textCounter" char_limit=250 id="Acivity_Details" id="Acivity_Details" name="Acivity_Details" cols="" rows="2" placeholder="Achievement Details..."
onKeyUp="textcounter4(document.Add_Assessment.Activity_Details,this.lang,250)"
lang="textcounter4" onKeyUp="textcounter4(document.Add_Assessment.Activity_Details,this.lang,250)" style="width:100%;"
value="'.$FormVars['Acivity_Details'].'"></textarea>');
echo('<h5><small id="textcounter4"></small></h5>');
?>
<h5 style="margin:2px 0px;"><small id="textCounter">(250)</small></h5>
<code style="clear:both;" id="Acivity_DetailsError">
<?php
if (array_key_exists('Acivity_Details', $Errors))
{
$tmp=$Errors['Acivity_Details'];
echo $PageErrors[$tmp][1];
}
?>
</code>
</div>
Any Help Appreciated
Take a look on this example, DEMO
$(document).ready(function() {
$('#textarea').on('keyup', function(e) {
e.preventDefault();
var _len = $(this).val().length;
$('#counter').text(_len);
});
});
Try this
$(document).ready(function() {
$('#Acivity_Details').keyup(function()
{
$('#textCounter').text('('+eval( 250- $('#Acivity_Details').val().length)+')');
});
});
Fiddle
Try this :
HTML
<textarea id="Acivity_Details"></textarea>
<div id="textCounter"></div>
JQuery
$(document).ready(function() {
$('#Acivity_Details').on('keyup', function(e) {
e.preventDefault();
var len = $(this).val().length;
$('#textCounter').text(len);
});
});
FIDDLE DEMO
Pure JS:
function countSymbols(obj)
{
var count = obj.value.length;
document.getElementById('counter').innerHTML = count.toString();
}
Html:
<form action="index.php" method="post">
<label>Text: <textarea onkeyup="return countSymbols(this);" name="t" id="t1"></textarea></label>
<p>Text counter: <span id="counter">0</span></p>
</form>
Firstly you don't want to do all those echo, stuff, you need to keep the html separate from your logic.
Although with raw php (php without frameworks its little difficult, but you can do it like this.
<div class="form-group col-md-12">
<div id="div_Description" name="div_Description" >
<div class="form-group col-md-12" style="padding-left:0px;">
<label>Description</label>
<textarea id="text"></textarea>
<span id="count"></span> charecters
<code style="clear:both;" id="Acivity_DetailsError">
<?php
render_page_errors($Errors);
?>
</div>
</div>
</div>
<script type="text/javascript">
// since i am not much of jquery
var $ = function(selector) {
var q = document.querySelectorAll(selector);
if (q.length == 1)
return q[0];
else
return q;
};
$("#area").addEventListener("keyup", function() {
var a = $("#area");
$("#count").innerHTML = a.value.length;
});
</script>
and now you can have a file like showpage_helpers.php
and put your:
function dump_page_errors($errors) {
if (array_key_exists('Acivity_Details', $Errors))
{
$tmp=$Errors['Acivity_Details'];
return $PageErrors[$tmp][1];
}
}
function render_page_errors($errors) {
$errors = dump_page_errors($errors);
// and put some for_each block and put the errors in an unordered list maybe
}
and autoload this file in your php view file.
in there