Hello i have the following code with problems, i'm trying to make it when you click on the output to insert it into the input field. Can you help me please, been trying for hours without any luck.
<script type="text/javascript">
var input = $('#CompanyName');
var output = $('#output');
var timer;
input.on('keyup', function() {
delaySearch(this.value);
});
function delaySearch(keywords) {
clearTimeout(timer);
timer = setTimeout(function() {
performSearch(keywords);
}, 1000);
}
function performSearch(keywords) {
$.ajax({
type: "POST",
url: "/print/order/search",
data: { query: keywords },
cache: false,
dataType: "json",
async: true,
success: function(data) {
for(var key in data) {
output.append('<li onclick="fill('+ data[key].ClientName +')">' + data[key].ClientName) + '</li>';
}
}
});
}
function fill(thisValue) {
input.val(thisValue);
clearTimeout(timer);
}
</script>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="CompanyName">Firma</label>
<div class="col-md-5">
<input id="CompanyName" onblur="fill();" name="CompanyName" type="text" placeholder="Firma" class="form-control input-md">
<ul id="output"></ul>
<span class="help-block"></span>
</div>
</div>
Uncaught ReferenceError: somevalue is not defined
Update:
After adding jquery ready function i noticed some errors around and fixed them here is an update on the code
<div class="form-group">
<label class="col-md-4 control-label" for="CompanyName">Firma</label>
<div class="col-md-5">
<input id="CompanyName" name="CompanyName" type="text" placeholder="Firma" class="form-control input-md">
<ul id="output"><li onclick="fill(Ionut)">Ionut</li></ul>
<span class="help-block">Nume Firma</span>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var input = $('#CompanyName');
var output = $('#output');
var timer;
input.on('keyup', function() {
delaySearch(this.value);
});
function delaySearch(keywords) {
clearTimeout(timer);
timer = setTimeout(function() {
performSearch(keywords);
}, 1000);
}
function fill(thisValue) {
input.val(thisValue);
}
function performSearch(keywords) {
$.ajax({
type: "POST",
url: "/print/order/search",
data: { query: keywords },
cache: false,
dataType: "json",
async: true,
success: function(data) {
for(var key in data) {
output.append('<li onclick="fill(' + data[key].ClientName + ')">' + data[key].ClientName) + '</li>';
}
}
});
}
});
</script>
onclick the error persists
Uncaught ReferenceError: fill is not defined
realseanp is onto the correct answer. I'll try to explain it a little better for you. When a browser starts processing and rendering a page, it loads top down. So your javascript scripts are being ran and evaluated before the DOM is created.
So your jquery selectors: var input = $('#CompanyName'); if you were to inspect them are going to be an empty array. They cannot find the #CompanyName element because it has not yet been rendered.
If you use jQuery's $(document).ready() function, then you can be assured that your code will not run until the dom is finished rendering, and therefore will find the elements as you intend them to. So in the end, your code will need to change to this:
$(document).ready(function(){
//Put your code in here.
//It will then fire once the dom is ready.
});
UPDATE:
Additionally, with your update. I'm noticing that the error is that 'fill' is not defined. fill being your onclick method. You have your js script evaluating after the dom is rendered. So at the time that the dom is rendered, and the tag with the onclick is rendered, no fill method yet exists. Two solutions:
Move the script above the dom, and place a var fill; outside of the $(document).ready so essentially this:
var fill;
$(document.ready(function(){
//your code
});
Don't use the onclick dom attribute, and instead use jquery to bind the event. So change
Ionut
to this:
<ul id="output"><li>Ionut</li></ul>
and inside the document.ready, add:
$('#output li').click(function(e) {
fill(/*your value/*)
});
You need to put your script below your HTML. That or wrap it in the jQuery Document ready function. And make sure you have jQuery loaded on the page, before your script
Related
I have a laravel application which shows some stats to my users.
On my front end blade, I'm displaying few widgets where each widget contain's a specific stat.
Following widget is to show number of total orders.
<div class="row mt-3" id="shopify_row1">
<div class="col-md-2" id="shopify_widget1">
<div class="jumbotron bg-dark text-white">
<img class="img-fluid pull-left" src="https://cdn0.iconfinder.com/data/icons/social-media-2092/100/social-35-512.png" width="32" height="32">
<h6 class="text-secondary mt-2 px-4">Shopify</h6>
<hr class="border border-white">
<h5 class="text-white">Total Orders</h5>
<span class="tot_o" id="tot_o">{{ $tot_o }}</span>
</div>
</div>
</div>
Like this widget, I have 5 more widgets to display 5 different stats.
In every widget initially I'm displaying stats for the current date, eg: if the total number of orders for the day is 0, it shows 0...
Then, I have added a a date picker as I can get the data only for a particular day.
<td>
<input id="date" class="date form-control" type="date">
</td>
And following is my jQuery...
<script>
$(document).on('change', '#date', function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'GET',
url : '/shopify_data',
data : {selected_date : $('#date').val()},
success:function(data){
$('#tot_o').empty();
$('#tot_sum').empty();
$('#avg_ov').empty();
$('#cus').empty();
$('#item_sum').empty();
$('#orders').empty();
var total_orders = data.tot_o;
var total_sales = data.sum;
var currency = data.crr;
var avg_ov = data.avg_ov;
var cus = data.cus;
var item_sum = data.item_sum;
var orders = data.orders;
$('#tot_o').append(total_orders);
$('#tot_sum').append(total_sales);
$('#avg_ov').append(avg_ov);
$('#cus').append(cus);
$('#item_sum').append(item_sum);
$('#orders').append(orders);
//console.log(total_orders);
},
timeout:10000
});
});
</script>
This entire code works perfectly, but now I need to add a loading gif till the updated results get displayed on the date change.
What changes should I do to above jQuery in order to add the loading gif...
There are multiple ways how you can create the loading gif. One would be to create an element in your blade template that is hidden or shown by using a class.
HTML:
<div class="loader hidden"></div>
CSS:
.hidden {
display: none;
}
jQuery:
const loader = document.querySelector('.loader');
$(document).on('change', '#date', function (e) {
loader.classList.remove('hidden');
// your other code..
}
And inside your success function you add the hidden class which should hide the loading element again.
success: function(data){
loader.classList.add('hidden');
// your existing code..
},
However, I would instead add a complete block, which ensures that on failure as on success the loading element is hidden.
$.ajax({
// your existing code..
complete: () => {
loader.classList.add('hidden');
}
}
You can place loading gif in any place of DOM with style="display: none".
Next, in your script before ajax you can show gif and after success or fail result hide it again:
<script>
let gif = $('.loading-gif'); // Your loading gif
$(document).on('change', '#date', function (e) {
gif.show(); // Show loading gif
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'GET',
url : '/shopify_data',
data : {selected_date : $('#date').val()},
success:function(data){
gif.hide(); // Hide gif
$('#tot_o').empty();
$('#tot_sum').empty();
$('#avg_ov').empty();
$('#cus').empty();
$('#item_sum').empty();
$('#orders').empty();
var total_orders = data.tot_o;
var total_sales = data.sum;
var currency = data.crr;
var avg_ov = data.avg_ov;
var cus = data.cus;
var item_sum = data.item_sum;
var orders = data.orders;
$('#tot_o').append(total_orders);
$('#tot_sum').append(total_sales);
$('#avg_ov').append(avg_ov);
$('#cus').append(cus);
$('#item_sum').append(item_sum);
$('#orders').append(orders);
//console.log(total_orders);
},
timeout:10000
});
});
</script>
I'm using ajax post to send my value to (uploadsignupeditadvcheck.php). After submit successfully, I need to refresh my div tag (galleryadv) to prepare for next submit. My ajax submit is successfully, but after refresh my jquery function is not working anymore. I appreciate you guys, can help on my situation. thank you.
index.php
<script>
function uploadadv(){
var idadv = document.getElementById("idadv").value;
var companynameadv = document.getElementById("companynameadv").value;
var usernameadv = document.getElementById("usernameadv").value;
var aboutmeadv = $("#aboutmedecsadv").val();
var catadv = document.getElementById("catadv").value;
var typeadv = document.getElementById("typeadv").value;
var keywordadv = document.getElementById("keywordadv").value;
var addressadv = document.getElementById("addressadv").value;
var countryadv = document.getElementById("countryadv").value;
var zipadv = document.getElementById("zipadv").value;
var stateadv = document.getElementById("stateadv").value;
var cityadv = document.getElementById("cityadv").value;
var urladv = document.getElementById("urladv").value;
var priceadv = document.getElementById("priceadv").value;
var advstamp = document.getElementById("advstamp").value;
var myData = 'idadv='+idadv+ '&companynameadv='+companynameadv+ '&usernameadv='+ usernameadv+ '&aboutmeadv='+aboutmeadv+ '&catadv='+catadv+ '&typeadv='+typeadv+ '&keywordadv='+ keywordadv+ '&addressadv='+ addressadv+ '&countryadv='+ countryadv+ '&zipadv='+ zipadv+ '&stateadv='+ stateadv+ '&cityadv='+ cityadv+ '&urladv='+ urladv+ '&priceadv='+ priceadv+ '&advstamp='+ advstamp;
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "uploadsignupeditadvcheck.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(data){
$('#messageeditcheckadv').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
};
</script>
<script>
var btn_edit = $(".avatar-galleryadv"),
btn_save = $(".avatar-previewgalleryadvsave");
btn_save.hide(0);
btn_edit.on("click", function() {
$(this).hide(0);
btn_save.fadeIn(300);
});
btn_save.on("click", function() {
$(this).hide(0);
btn_edit.fadeIn(300);
});
</script>
<script>
$( ".fa-map-marker" ).click(function() {
$( ".navtumbler" ).toggle( "fast" );
});
</script>
<div class="galleryadv">
<div class="avatar-galleryadv">
<div class="avatar-editgalleryadv">
<input type='file' id="uploadFileadv" accept=".png, .jpg, .jpeg" />
<label for="imageadv"></label>
</div>
<div class="avatar-previewgalleryadv">
<div id="imagePreviewgalleryadv" style="background-image: url(images/whitecamera.png); background-color:#181818; background-size:contain; background-repeat:no-repeat;">
</div>
</div>
</div>
<div class="avatar-previewgalleryadvsave">
<i class="fa fa-floppy-o" aria-hidden="true" id="uploadimageadv" style="margin:1px 0px 0px 0.4px;"></i>
</div>
<div class="igVideoData" style="color:#FFF; float:left;">
<i class="fa fa-map-marker spriteTemplate" aria-hidden="true" ></i>
</div>
</div>
uploadsignupeditadvcheck.php
$(".galleryadv").load(location.href+" .galleryadv>*");
You're overwriting dom elements that event handlers were attached to before. So you attach click events to buttons first, and then you load fresh HTML and overwriting the buttons that had handlers attached to so the new buttons have no event handlers attached to, that is why they do not respond to click events.
Either attach event handler to parent element that does not get overwritten, or reattach event handlers after you load and overwrite with new html.
I would probably go with attaching events to their parent, so it gets handled when event propagate up the dom tree.
var buttons_parent = $('.galleryadv');
buttons_parent.on('click', '.avatar-galleryadv', function(){
$(this).hide(0);
$('.avatar-previewgalleryadvsave').fadeIn(300);
});
buttons_parent.on('click', '.avatar-previewgalleryadvsave', function(){
$(this).hide(0);
$('.avatar-galleryadv').fadeIn(300);
});
And this goes instead of btn_edit.on("click", function() {... and btn_save.on("click", function() {.... Also I don't refer to buttons inside handlers by their reference saved in the variables because these will be invalid after overwriting them so I always look for them by their class names.
This way even when buttons are overwriten the handlers that handles their click events are intact.
Trying to search in Wikipedia by user's input but it doesn't work for some reason. First I thought it could be due to cross domain problem. But .ajax should help with that.
Here is codepen: http://codepen.io/ekilja01/pen/pRerpb
Here is my HTML:
<script src="https://use.fontawesome.com/43f8201759.js">
</script>
<body>
<h2 class="headertext">WIKIPEDIA <br> VIEWER </h2>
<div class="row">
<div class="col-10-md">
<input class="searchRequest blink_me" id="cursor" type="text" placeholder="__"></input>
</div>
<div class="searchIcon col-2-md"> </div>
</div>
<div>
<p class=results></p>
</div>
</body>
Here is my jQuery:
$(document).ready(function() {
var icon = "<i class='fa fa-search fa-2x'></i>";
$('#cursor').on("keydown", function() {
$(this).removeClass("blink_me");
var searchIcon = $(".searchIcon");
searchIcon.empty();
if ($(".searchRequest").val().length > 0) {
searchIcon.append(icon);
}
searchIcon.on("click", function() {
console.log("clicked!");
var search = $(".searchRequest").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + search + "&format=json&callback=?";
$.ajax({
dataType: "jsonp",
url: url,
success: function(data) {
$(".results").html(data[0]);
console.log(data[0]);
}
});
});
});
});
What am doing wrong? Please help.
There's an error in the order of load for your js.
The data object contains the text of the results in the array with index 2, which i assume is what you want to show, change it to
$(".results").html(data[2]);
You can check a modified version of your original code here
http://codepen.io/anon/pen/mRmGXG
I am trying to my migrate my website to angular but slowly. Current scenario is i am having a plain HTML login page in which there is a link to open a forget password popup. I have migrated the Forget password page to Angular. So what i am doing is when the user clicks on the link, i load the angular library, controller and application through $.getscript and then do a AJAX call to load the ForgetPassword page content in the popup. I can see in console evrything has loaded prioperly but error comes when i try to bootstrap. Please find below my JS code.The error i am getting in console is "ReferenceError: angular is not defined angular.bootstrap(document, ['myApp']);"
$(document).ready(function () {
$("#complementary-nav ul li a#popup").bind("click", function () {
loadfiles(function () {
OpenPopup();
angular.bootstrap(document, ['myApp']);
});
});
});
// Code to open in pop up
function loadfiles(callback) {
var scripts = ['/js/angular.min.1.2.9.js', '/js/Controller.js', '/js/application.js'];
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {});
}
if (typeof callback === "function") {
callback();
}
}
function OpenPopup() {
var url = "/dev/Forgot-Password.aspx";
$.ajax({
type: "GET",
async: false,
contentType: "charset=UTF-8",
url: url,
success: function (data) {
$("#common-popup").html("").append($(data));
$("#common-popup_overlay").fadeIn(500);
},
error: function () {
console.log("error")
}
});
}
The Forgot Password HTML looks like this
<div ng-controller="ForgotPasswordController" id="lostPasswwordOverlayContent" class="overlayContent">
<p>
<label>E-Mail<span class="mandatory">*</span></label>
<input type="email" ng-class="{'input-error':(_ServerForm.email.$dirty && _ServerForm.email.$error.emailValidate) || (blankSubmit && _ServerForm.email.$invalid)}" ng-model="user.email" email-validate required name="email" placeholder="" maxlength="100" id="EmailAddress" />
<span class="ui-state-error h5-message" ng-show="(_ServerForm.email.$dirty && _ServerForm.email.$error.emailValidate) || (blankSubmit && _ServerForm.email.$invalid)">
<span class="h5-arrow"></span>
<span class="h5-content">Invalid Email</span>
</span>
</p>
<div class="button buttonSimple buttonRight greenbutton forgotpassword">
<a name="fgtpassword" id="fgtpassword" href="#" class="" ng-click="submitform($event)"><span>Submit<span class="visual"></span></span></a>
</div>
I have tested the functionality seperately for this page and it works fine if opened an independent HTML page whereas when i try to make changes and open it as a popup, i am getting error
I never used $.getScript() but according to the documentation you can provide a callback when the scripts have arrived and have been executed. Why don't you call your own callback then?
function loadfiles(callback) {
var scripts = ['/js/angular.min.1.2.9.js', '/js/Controller.js', '/js/application.js'];
var scriptsAlreadyFetched = scripts.length;
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {
scriptsAlreadyFetched--;
if (typeof callback === "function" && scriptsAlreadyFetched== 0) {
callback();
}
});
}
}
#meilke Yes the solution worked for me. But i found an alternative for doing it .
I am using the modernizr approach for the loading the JS files. With this approach i am also able to load CSS files together with the JS files
$("#complementary-nav ul li a#popup").bind("click", function () {
loadfiles(function () {
angular.bootstrap(document, ['myApp']);
});
});
function loadfiles(callback) {
var modernizrLoad = [{ load: ['//code.angularjs.org/1.2.8/angular.min.js', '/js/application.js', '/js/Controller.js', '/css/Styles_v2.css', '/css/tyles.css'], complete: function () { OpenPopup(callback); } }];
Modernizr.load(modernizrLoad);
}
I have an Ajax code like this:
$j(document).ready(function () {
function loading_show() {
$j('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$j('#loading').fadeOut();
}
function loadData(page) {
loading_show();
$j.ajax({
type: "POST",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
var $response = $j(msg);
// Query the jQuery object for the values
oGlobal = $response.filter('#Z').text();
$j("#container").ajaxComplete(function(event, request, settings) {
loading_hide();
$j("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$j('#container .pagination li.active').live('click', function () {
var page = $j(this).attr('p');
loadData(page);
});
});
Im getting this response:
<div id="container">
<div id="Z">JuanFernando</div>
<div id="q">
<div class="pagination">
<ul>
<li p="1" class="inactive">First</li>
<li class="inactive">Previous</li>
<li p="1" style="color:#fff;background-color:#006699;" class="active">1</li>
<li p="2" class="active">2</li>
<li p="2" class="active">Next</li>
<li p="2" class="active">Last</li>
</ul>
<input class="goto" size="1" style="margin-top:-1px;margin-left:60px;"
type="text">
<input id="go_btn" class="go_button" value="Go" type="button"><span class="total" a="2">Page <b>1</b> of <b>2</b></span>
</div>
</div>
</div>
I want to extract "JuanFernando" in order to show in div container but alone and I want that the rest of the response could be show in other different div for example: container2.
ajaxComplete is not what you want to use here, especially inside your success function. You want your success function to look something like this:
success: function (msg) {
loading_hide();
var $response = $j(msg);
// Query the jQuery object for the values
oGlobal = $response.find('#Z').text();
$j("#container").html(oGlobal);
$response.find('#Z').remove();
$j('<div id="container2"></div>').html($response.html()).appendTo('body');
}
We're just taking the oGlobal (which should be JuanFernando in this case) and sticking it in the #container. After that, remove the #Z div from the response, and stick the rest inside of a new #container2, and append it to the body, or wherever you'd like it.
Here's an "adapted" fiddle.
Basically the only thing that changes with you code is
replace
oGlobal = $response.filter('#Z').text();
with
oGlobal = $response.find('#Z').text();
also, see MattDiamant's answer concerning ajaxComplete.