Div does not refresh when last character is deleted from input - javascript

I'm currently making a search function using a onkeyup="Search();" like this:
<input type="text" id="IDsearch" onkeyup="Search()" autofocus>
The function for it is:
<script type="text/javascript">
function Search() {
var inputVal = $('#IDsearch').val();
$.post('searchTest.php', {postname: inputVal},
function (data) {
$('#IDsearch').val(data)
});
$('#divRefresh').load('searchTest.php');
}
</script>
Yes, I am using the same file to both put the value in a php $_SESSION['value']; AND to store the new div data. That's no problem, it works, it does fine.
But when I delete my last character from my search box, I need to press backspace twice in order for my div to update.
Say I had a textbox with "a" in it. I will press backspace to update the a, and nothing will happen. Once I press backspace again, my div will update and post all the original values again.
Am I missing something obvious?
It's supposed to work the same way http://www.datatables.net/ does.
I have asked a question about this program before, but not about this issue, I hope it's not a problem.

I would go throught $("#IDsearch").keyup(function(){});
Tried your code with the function and didn't work, even with $("#divRefresh").html(theInputOfYours); The other way I mention to you works perfectly, even with backspace.
$(document).ready(function() {
$("#IDsearch").keyup(function() {
var value = $(this).val();
var posting = $.post("your_php_file.php", {val: value})
posting.done(function( data ) {
$( "#divRefresh" ).html(data);
});
});
});
The posting is a very basic example I can give, I use to go with $.ajax() function

Unfortunately, the behavior of keyup/keypress/keydown can be finicky sometimes, especially across different browsers.
A possible solution to ensure changes are tracked would be a listener that would track changes via a setInterval function that runs at an interval you specify.

Related

Tampermonkey: Trigger event does not work for element

I'm trying to add some functionality using Tampermonkey on top of a providers angular application but I'm stuck at this simple thing. I can't replicate the issue using CodePen so we're going to have to go for theories and suggestions. I'll try to be as specific as I can.
Adding this interval when the page loads to check when an input with the id serialNumberInput is available. Then I'm adding a dropdown to the form, and attach an onChange event to it to update the serial input field with the value of the selected option. However, the trigger parts just never happens. It does work when I enter them manually, but not with the script.
var populateSerialNumbersTimer = setInterval(function(){
var serial = $("input#serialNumberInput");
if($(serial).length >= 1){
$(serial).css("display", "inline").css("width", "50%");
$(serial).after(deviceToSerialSelectionHTML);
$("select#deviceToSerial").on("change", function(){
$(serial).val($("select#deviceToSerial").val());
$(serial).trigger("change");
$(serial).trigger("blur");
});
clearInterval(populateSerialNumbersTimer);
}
}, 200);
I've thought about it and considering how the serial number ends up in the text field the field must be accessible. Maybe it's that the events that I'm trying to trigger has not been declared at the time of the function declaration?
Suggestions much appreciated.
It looks like jQuery tries to cache the event somehow. This is how I solved it with native javascript in case someone else is interested:
function triggerEvent(e, s){
"use strict";
var event = document.createEvent('HTMLEvents');
event.initEvent(e, true, true);
document.querySelector(s).dispatchEvent(event);
}
$("select#deviceToSerial").on("change", function(){
serialNumberInput.val($("select#deviceToSerial").val());
triggerEvent("change", "input#serialNumberInput");
triggerEvent("blur", "input#serialNumberInput");
}

jQuery form input field present even before document.ready function is called

I am facing a weird issue. I am relatively new to JavaScript jQuery.
When I refresh the page the address input field doesn't get cleared, while zip code and email fields do get cleared.
I tried $('#input_address').get(0).value='';
which clears the field. But I don't want it to happen when the user comes back from page 2 to page 1. Only on refresh should the fields be cleared.
The email and zip code works perfectly in both scenarios: refresh page and page2 to page1 navigation.
$(document).ready(function() {
console.log("doc ready function");
// $('#input_address').get(0).value='';
// togglePlaceholder($('#input_email').get(0));
// togglePlaceholder($('#input_zip').get(0));
togglePlaceholder($('#input_address').get(0));
$('input, select, textarea').each(
function() {
var val = $(this).val().trim();
if (val.length) {
$(this).addClass('sample');
}
});
$('input, select, textarea').blur(function() {
if ($(this).val())
$(this).addClass('sample');
else
$(this).removeClass('sample');
});
$('input, select, textarea').focus(function() {
console.log("focused");
if ($(this).val() == '') {
$(this).removeClass('invalid');
$(this).addClass('sample');
}
});
})
function togglePlaceholder(inputElement) {
var inputAttr = inputElement.getAttribute("placeholder");
inputElement.placeholder = "";
inputElement.onblur = function() {
this.placeholder = "";
}
inputElement.onfocus = function() {
this.placeholder = inputAttr;
}
}
.sample ~ label {
font-size: 1em;
top: -10px;
left: 0;
font-size: 1em;
color: #F47B20;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-field col s6 col-xs-12">
<input type="text" onblur="togglePlaceholder(this);" onfocus="togglePlaceholder(this);" placeholder="123 Example Street" id="input_address" />
<label for="input_address">Street Address</label>
</div>
So... you have two problems.
(1) Auto-completion is what refills the widgets automatically,
(2) You need to know what button was clicked to react accordingly.
Auto-Completion
In regard to the auto-completion, it most certainly happens right after the first set of scripts ran within the jQuery ready() function.
There are two ways to remove auto-completion, but really, I do not recommend either one, although I would imagine that you'll need to if your requirements are set in stones...
(a) Ask for the input widget to not even autocomplete
<input ... autocomplete="off" .../>
(b) Run your script with a timer so it happens after the auto-completion. Instead of initializing in the ready() function, you initialize in a sub-function that runs after a timer times out.
$(document).ready(function() {
setTimeout(function(){
// ...put your initialization here...
// the autocompletion data should have been taken care of at this point
}, 0);
});
Note that you can use a number large than 0 for the timeout delay, but in most cases 0 will work just fine to run the sub-function after releasing the current thread once and thus given the system time to work on the auto-completion and then call your function. With 0 it should be so fast that you should not even see the <input .../> tag flash.
Side note: you may also want to place the inner function in an actual function as in:
function init_stuff()
{
// ...your initialization code goes here...
}
$(document).ready(function() {
setTimeout(init_stuff, 0);
});
If you expect your initialization to continue to grow, this can be a lot cleaner long term.
Which button gets clicked
The next problem is to know whether that code should run or not. So you need an extra if() statement for that purpose.
There are several hacks on this stackoverflow page in that regard. However, I'm not exactly sure how you really know in the newly loaded page, that you had a Refresh or a Back button click.
From the code I see there, the loading of the page's content would 100% happen in AJAX and therefore you perfectly know which button was clicked, you just reimplemented the functionality. You'll have to search stackoverflow some more to find out how to do that. I strongly suggest that you write tests with one piece of functionality at a time to determine what is going on.
Note that will make having the initialization function separate quite useful since after reloading the page, you will be responsible to call that function (when you want the reset to happen) or not! In other words, if the Back button was clicked, load the HTML of the previous page (i.e. Page 1 in your example) and display it. Done. When clicking the Refresh button, load the HTML of the current page and call the reset function (it could also be that the Refresh is the default and you do not want to handle that button since it will anyway clear as expected.)
For a beginner, that's going to be an interesting piece of work!

Prevent typeahead.js dropdown from closing on select

How can I prevent a typeahead dropdown from closing when an item is selected? I've tried using preventDefault like this:
$('#q').bind('typeahead:selected',function(obj, datum, name) {
...
obj.preventDefault();
});
But no success.
Edit:
I've managed to "fix" this by building Typeahead with lines 217-218 commented from typeahead_views.js:
byClick && utils.isMsie() ?
utils.defer(this.dropdownView.close) : this.dropdownView.close();
But there has to be another way without modifying source files?
Had the same problem and the (very easy) solution doesn't seem to be documented anywhere
$(document).on('typeahead:beforeclose', function(event, data) {
event.preventDefault()
})
(this just prevents the dropdown from closing at all which can be very helpful during development, use 'typeahead:beforeselect' if you want to prevent closing just on selet).
Trigger the focus of the input on the closed callback.
$('#typeahead-input').on('typeahead:closed', function(e, d) {
$('#typeahead-input').focus();
});
I'm working on typeahead inside tokenfield so the first part is me accessing the Typeahead.dropdown object, which in itself took some hunting.
Tried toying with isOpen or overwriting close functions, in the end closest I got was this. Breaking down the marshalling of events. You'd have to reimplement any saving of values etc, basically the first 3 lines of Typeahead.select.
I myself was blocked at being able to put a form (focus stays in input field) in the dropdown and still a bit more hunting if were to put something interactive in there. Think I'll go for a roll-your-own solution on this one but might help someone who just wants to block the closing, put the original function in a var to put it back in place when you're finished.
$('input[id="test"]').data('bs.tokenfield')
.$input.data('ttTypeahead').dropdown.trigger = function(e) {};
Also this has potential:
$('input[id="test"]').data('bs.tokenfield')
.$input.data('ttTypeahead').eventBus.trigger = function(e) {};
A simpler way:
input.data('tt-typeahead')._selectOld = input.data('tt-typeahead')._select
input.data('tt-typeahead')._select = function(datum) {
if (false)
this._selectOld(datum)
}

Making a basic Javascript calculator

jsfiddle demo
Bear with me, total newb here.
I'm trying to make a simple multiplication calculator, as a experimentation with Javascript.
The catch is that -
No libraries, just pure javascript.
Javascript must be unobtrusive.
Now, the problem arises, that it doesn't give the value out.
When I do this locally, answer has a value of NaN, and if you hit Submit it stays that way, BUT, if you press the back button, you see the actual result.
In the JSFiddle, much is not shown, except for the fact that it simply doesn't work.
Please tell me, is it even possible to make an unobtrusive calculator? How?
(PS. I was taking a bit of help from sciencebuddies, just to see basic syntax and stuff, but I found it can't be done without code being obtrusive)
I realize you're probably just getting started and don't know what to include, remove, and whatnot. But, good advice here, clearly label your elements so you can understand them, and pare it down to the smallest possible code you need for it to work (even less, so you can build it up).
Here is your code reworked:
HTML
<div>
<input type="text" id="multiplicand" value="4">
<input type="text" id="multiplier" value="10">
<button type="button" id="multiply">Multiply</button>
</div>
<p id="result">
The product is: <span id="product"> </span>
</p>
Javascript
window.onload = function(){
var button = el('multiply'),
multiplicand = el('multiplicand'),
multiplier = el('multiplier'),
product = el('product');
function el(id) {
return document.getElementById(id);
};
function multiply() {
var x = parseFloat(multiplicand.value) || 0,
y = parseFloat(multiplier.value) || 0;
product.innerHTML = x * y;
}
button.onclick = multiply;
};
http://jsfiddle.net/userdude/EptAN/6/
A slightly more sophisticated approach, with add/subtract/multiply/divide:
http://jsfiddle.net/userdude/EptAN/9/
You have to change the submit button so that it doesn't submit the form. Right now clicking "Submit" causes the form submits to the same page which involves a page reload.
Change the <input type="submit" id="submitt"> to <button type=button> and it should work.
You can probably do without the <form> element in the first place. That'll stop clicking enter in your text input from reloading the page.
Your example has a couple of problems:
The form still submits. After the JS changes the value, the submit will cause the page to reload, and that work you've done setting the answer value is wasted.
You're trying to do this stuff right away. In the header, none of the body has been parsed yet (and thus, the form elements don't even exist). You'll want to wait til the page is loaded.
The script hijacks window.onload. If you don't have any other scripts on the page, that's fine...but the whole point of unobtrusive JS (IMO) is that nothing breaks whether the script is there or not.
Fixed, we have something kinda like:
// Wrap this onload in an IIFE that we pass the old onload to, so we can
// let it run too (rather than just replacing it)
(function(old_onload) {
// attach this code to onload, so it'll run after everything exists
window.onload = function(event) {
// run the previous onload
if (old_onload) old_onload.call(window, event);
document.getElementById('Xintox').onsubmit = function() {
var multiplier = +this.multiplier.value;
var multiplicand = +this.multiplicand.value;
this.answer.value = multiplier * multiplicand;
return false; // keep the form from submitting
};
};​
})(window.onload);
Note i'm attaching the meat code to the form, rather than the button, because hitting Enter in either of the factor boxes will trigger a submit as well. You could still attach to the button if you wanted, and just add a submit handler that returns false. But IMO it's better this way -- that way the form works just the same with JS as without (assuming the script on the server fills in the boxes appropriately), except it won't require a round trip to the server.

Input text clear when I try to submit for a search

Hello I have the following problem. I the site http://www.telefonkoll.se when I enter a number in the search and press the button then the text clears automatically and the result page return me all the results. If I don't use the jquery code it works correctly.
My jQuery code is this:
$("document").ready(function() {
$("#mod_search_searchword").attr("value","Sök telefonnummer här");
});
$("#mod_search_searchword").live('focus', function (event) {
$("#mod_search_searchword").focus(function() {
$(this).val("");
});
});
$("#mod_search_searchword").live('blur', function (event) {
$("#mod_search_searchword").blur(function() {
if ($(this).val() == ""){
$(this).val("Sök telefonnummer här"); }
});
});
What I want to do with the above code is to clear the current text when the user click there. If it write something to still there, if not to return the initial text. It looks to work correctly but when I try to submit the data something wrong obviously happen. I don't know if it's the code or something I don't know.
Avoid reinventing the wheel. Use one of the many jQuery watermark plugins available.

Categories