Detect change in an <input> field controlled by a slider - javascript

I have a form with a double-handles slider:
<form id="advancedSearch" action="modules/advanced_search.xq" method="post" onsubmit="advancedSearch(this);">
<div class="slider" id="slider" data-aria-valuemin="1725" data-aria-valuemax="1786" data-slider="data-slider" data-start="1725" data-end="1786" data-initial-start="1725" data-initial-end="1786">
<span id="handle1" class="slider-handle" data-slider-handle="data-slider-handle" role="slider" tabindex="1" aria-controls="dateFrom"/>
<span id="handle2" class="slider-handle" data-slider-handle="data-slider-handle" role="slider" tabindex="1" aria-controls="dateTo"/>
[...]
<input type="number" max="1786" min="1725" id="dateFrom" name="dateFrom"/>
</div>
<div class="cell small-2">
<input type="number" max="1786" min="1725" id="dateTo" name="dateTo"/>
[...]
</form>
It all works well.
Now, I'd like to call the function advancedSearch() when changing the slider's handle, without having to hit 'submit' each time.
Adding a oninput='advancedSearch(this.form); return false;' to the <input> elements does the trick only if I change the numbers inside the <input> field. When using the sliders, although document.getElementById('dateFrom').value does get changed, does not trigger the function. onchange also doesn't work. How can I call the function when changing the number by using the slider itself, other than changing the numbers inside the <input> field manually?
Adding a separate function:
document.getElementById('dateFrom').addEventListener('change', (event) => {
var formData = document.getElementById('advancedSearch')
advancedSearch(formData)
});
yields the same result.

Thanks to Prikesh Savla for pointing me towards the changed.zf.slider event. Unfortunately when implementing that with:
$("#slider").on('change changed.zf.slider', function(){ { var formData = document.getElementById('advancedSearch') advancedSearch(formData); }});
the page calls the function when loading it (either refreshing or landing there). After some troubleshooting I haven't been able to find the reason for that. In the end I'm adding this code:
document.querySelector('.slider').addEventListener("click", function () {
advancedSearch(document.getElementById('advancedSearch'));
});
document.getElementById('dateFrom').addEventListener("input", function () {
advancedSearch(document.getElementById('advancedSearch'));
});
document.getElementById('dateTo').addEventListener("input", function () {
advancedSearch(document.getElementById('advancedSearch'));
});
which does what I want, although I appreciate that it's not the most elegant solution.

Related

parsley.js does not work for ckeditor textarea

I wrote code for my form with parsley.js validator, however it works fine except CKEditor textareas. Where can be the problem? Here is screenshot
Here is my code:
<script type="text/javascript">
CKEDITOR.on('instanceReady', function(){
$.each( CKEDITOR.instances, function(instance) {
CKEDITOR.instances[instance].on("change",function(e) {
for ( instance in CKEDITOR.instances)
CKEDITOR.instances[instance].updateElement();
});
});
});
</script>
<h2 class="heading">Description</h2>
<div class="controls">
<textarea name="description" id="description" required="" data-parsley-errors-container="#description-errors" data-parsley-required-message="Это поле необходимо!"></textarea>
</div>
<div style="margin-bottom: 20px;" id="description-errors"></div>
<script>
CKEDITOR.replace('description');
</script>
<h2 class="heading">Purpose</h2>
<div class="controls">
<textarea name="purpose" id="purpose" required="" data-parsley-errors-container="#purpose-errors" data-parsley-required-message="Это поле необходимо!"></textarea>
<div style="margin-bottom: 20px;" id="purpose-errors"></div><br><br>
<button type="submit" name="submit">Submit</button>
</div>
<script>
CKEDITOR.replace('purpose');
</script>
Your issue is related to the required attribute. After, this line:
CKEDITOR.on('instanceReady', function () {
you need to add such an attribute again, for each text area, because lost during CKEDITOR init phase (i.e.: CKEDITOR.replace('purpose');).
For a specific textarea you can write:
$('#description').attr('required', '');
For all the textareas belonging to the form:
$('form textarea').attr('required', '');
From your comment:
When the error shows in other inputs and when I type something it removes automatically. But in textareas it does not leave
In order to solve this part, on CKEDITOR change event, you need to trigger parsley validation. The below line does the trick:
$('form').parsley().validate();
The updated code (jsfiddle here):
CKEDITOR.on('instanceReady', function () {
$('form textarea').attr('required', '');
$.each(CKEDITOR.instances, function (instance) {
CKEDITOR.instances[instance].on("change", function (e) {
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
$('form').parsley().validate();
}
});
});
});
It's always so much easier to answer questions if you provide a minimal working example...
ckeditor hides the <textarea> and fills it in via Javascript.
Maybe the issue is that the error container is in the wrong place.
It's also very possible that ckeditor doesn't trigger the input event (not very well known). If that's the case, the following code should resolve the issue:
$('textarea').on('change', function() { $(this).trigger('input') })
Please update if this works or not.

How to Input and Output Javascript?

Ok Guys I need help in this case and please help if you can :(
I have following div created with text-type input
<div class="footer">
<div id="footerInner">
<form>
<input type="text" name="enter" value="" id="input"/>
</form>
</div>
</div>
I have also created above .footer .mainBody
<div class="mainBody">
<script src="Scripts/main.js">
var h = document.getElementById('input').value;
document.write(h);
</script>
</div>
And I have included Javascript in it
I want to work it this way: when I input text in input tag to appear in .mainBody div.
And also do I need button to submit input or it can be done with key press for Ex. "Enter"?
Guys onkeyup="writeThis()" isn't working it just reloads page :(
To execute some events on keyevents, you need to write the onkeyup or onkeydown or any other key function in the element. And in that attribute you can add the function's name which would respond to the event. I will write my function's name as writethis() which will write the value to the div.
You then need to use this:
<input type="text" id="input" onkeyup="writethis()" />
And the function would be:
function writethis() { // the function
var h = document.getElementById('input').value; // the value
document.getElementsByClassName('mainBody').innerHTML = h; // the input
}
This way, you will get the input written on a keypress!
You can also try and use some keyevents such as:
if(event.keyCode == 13) { // enter key event
/* key code for enter is 13
* do what so ever you want */
}
Ok, try this as your JS script content in html head section:
function writeOnBody() {
var inputText = document.getElementById('input').value;
var mainBodyEl = document.getElementById('mainBody');
mainBodyEl.innerHTML = inputText;
}
your HTML code:
<div class="footer">
<div id="footerInner">
<form>
<input type="text" name="enter" value="" id="input" onkeyup="writeOnBody()" />
</form>
</div>
</div>
<div id='mainBody' class="mainBody"></div>
I hope it helps. JSFiddle sample: http://jsfiddle.net/amontellano/JAF89/
var h = document.getElementById('input').value; // the value
document.getElementsByClassName('mainBody').innerHTML = h;
avoid using getElementsByClassName instead give you div a id and use getElementById..
rest is in my opinion the best solution..
and yes you can also you a button also all you have to do is call you function on onclick event like this
<button onclick="functionZ()">click me</button>
and define that functionZ in your java script
What we are doing here is..
Adding a button and a click event upon it..such that when that button will be clicked it will call a function for us..
Make sure to add your scripts in lasts part of your page as page loads from top to bottom so its good practice to add scripts just near to end of body

jQuery File Upload not working when file input dynamically created

i am using this jquery uploader (http://blueimp.github.io/jQuery-File-Upload/basic.html) and it works fine when the file input is put in the raw code of the site, however i am dynamically appending the fields with jquery and it doesnt work. here is the jquery to trigger the upload:
$('.fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
alert(file.name);
//$('<p/>').text(file.name).appendTo(document.body);
});
}
});
and this is what SHOULD trigger the upload:
<input class="fileupload" type="file" name="files[]" data-url="uploads/">
Here is the code that is appended by jquery:
$(document).on('click','.addItem', function(){
$('<!--ROW START-->\
<form class="widget-content item" data-url="uploads/">\
<div class="row">\
<div class="col-md-3"><input type="text" class="form-control" name="itemName[]"></div>\
<div class="col-md-3"><textarea class="auto form-control" name="itemDescription[]" cols="20" rows="1" style="word-wrap: break-word; resize: vertical;"></textarea></div>\
<div class="col-md-3"><textarea class="auto form-control" name="itemCondition[]" cols="20" rows="1" style="word-wrap: break-word; resize: vertical;"></textarea></div>\
<input type="hidden" class="itemId" name="itemId[]" value="">\
<input type="hidden" name="itemInventoryId[]" value="<?=$_GET["inventory_id"]?>">\
<input type="hidden" name="itemParent[]" value="'+$(this).closest('.formHolder').data('parent-room')+'">\
<div class="col-md-2">\
<div class="fileinput-holder input-group">\
<input class="fileupload" type="file" name="files[]">\
</div>\
</div>\
<div class="col-md-1 align-center"><i class="save icon-ok large"> </i> <i class="delete icon-trash large"> </i></div>\
</div>\
</form>\
<!--/ROW END-->').fadeIn(500).appendTo($(this).parents().siblings('.items'));
$(this).parent().parent().siblings('.widget-header, .header-margin, .hide').removeClass('hide').fadeIn();
});
like i say, when i add it into the actual code, not dynamically its fine. Can someone help please?
This is because you bind fileupload event before element is added.
Try moving your code into callback function which will be executed after you create input element. Since appendTo() doesn't support callback, you can use each(callback):
$('code_that_you_append').appendTo('some_element').each(function () {
// here goes $('.fileupload').fileupload({ ... }) function
});
If you need to bind event to .fileupload in multiple places in code, you can create a function to avoid code repetition, like this:
function bindFileUpload() {
$('.fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
alert(file.name);
});
}
});
};
and then call it in the callback, like before:
$('code_that_you_append').appendTo('some_element').each(function () {
bindFileUpload();
});
I've created a little demo. It binds click instead of fileupload to simplify things (fileupload is external plugin...), but the general rule stays the same.
You need to use the jQuery live() function.
This tip I found worked for me.
jQuery fileupload for dynamically added input field
Just bind the upload function with a static identifier at first. Here, 'document' is the static identifier. You can use anything like this that has not been added dynamically. Usually, document is used more often.
$(document).on('click', '.fileupload', function () {
$('.fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
alert(file.name);
//$('<p/>').text(file.name).appendTo(document.body);
});
}
});
});
N.B: Please see accepted answer first.
I think accepted answer has little mistake. I just trying to recover that.
On #Michał Rybak little demo you will see that every time we click add item another click event also will be added to previous added new link( add more then new link and see first new link show alert number of time new item). Because every time it add new link we again add click event to all new link elements.
$('<p>new link</p>').appendTo('body').each(function () {
// bindClickToLink call every 'new link' and add click event on it
bindClickToLink();
});
To solve that issues, instead add click event to all item we just add to newly created item. Here is my solution my demo .

Flip text input fields between elements, including user-created value attribute

Hi I'm trying to flip the input fields between two div elements. However, if a user enters text into the fields, the text disappears after the flip happens. Is there a way to make sure this value attribute is flipped too? Thanks.
Javascript:
function Flip ()
{
var oldslave = $('div.slave').html();
var oldmaster = $('div.master').html();
$('div.slave').html(oldmaster);
$('div.master').html(oldslave);
}
HTML:
<div class="master">
<input type="text" name="master" id="master" size="42">
</div>
<input type="button" id="button1" onclick="Flip()" value="Flip">
<div class="slave">
<input type="text" name="slave" id="slave" size="42" class="slavefield">
</div>
You can use clone method like this:
function Flip() {
var oldslave = $('div.slave input').clone();
var oldmaster = $('div.master input').clone();
$('div.slave').html(oldmaster);
$('div.master').html(oldslave);
}
http://jsfiddle.net/MaESg/
There is also another variant to achieve the same without using clone:
function Flip() {
$('.master').find('input').appendTo('.slave').prev().appendTo('.master');
}
This one is preferable because appending (moving) nodes much more effective than recreating.
http://jsfiddle.net/MaESg/1/

JQuery Dropdown behavior

really new to JQuery.. like 2 hours new. Began to write a drop down menu for a login box like this:
HTML:
<button id="loginButton">Login</button>
When you hover over that, this JQuery runs:
$('#loginButton').live('hover', function() {
login_drop();
});
function login_drop(){
$('#loginBox').fadeIn();
}
$('#loginButton').live('hover', function() {
login_away();
});
function login_away(){
$('#loginBox').fadeOut();
}
And then this HTML DIV appears directly under the button:
<div id="loginBox">
<label for="email_B">Email Address</label>
<input type="text" name="email_B" id="email_B" />
<label for="password">Password</label>
<input type="password_B" name="password_B" id="password_B" />
<input type="submit" id="login" value="Sign in" />
<label for="checkbox"><input type="checkbox" id="checkbox" />Remember me</label>
<span>Forgot your password?</span>
</div>
and the CSS on that DIV is this:
#loginBox {
position:absolute;
top:70px;
right:100px;
display:none;
z-index:1;
}
This all works, but the behavior of it stinks. How do I make it so you can hover over the button put your mouse in the newly appeared DIV and the div won't fade away until your mouse leaves the div?
Sorry if my coding stinks.
Thanks a bunch guys!
--------------------------------EDITS AKA the ANSWERS--------------------
So for all of you reading this down the line. There are so many ways of making this work depending on how you want the user to interact with it.
Here is way 1...This way the login box fades out when your mouse leaves the login button. This is a quick way fo making it work. This answer is thanks to elclanrs besure to Up 1 his answer below if you like this.
JQuery:
$(function(){
$('#loginButton').mouseenter(function(){ $('#loginBox').fadeIn(); });
$('#login').mouseout(function(){ $('#loginBox').fadeOut(); });
});
HTML:
<div id="loginBox">
<label for="email_B">Email Address</label>
<input type="text" name="email_B" id="email_B" />
<label for="password">Password</label>
<input type="password_B" name="password_B" id="password_B" />
<input type="submit" id="login" value="Sign in" />
<label for="checkbox"><input type="checkbox" id="checkbox" />Remember me</label>
<span>Forgot your password?</span>
</div>
CSS:
#loginBox {
position:absolute;
top:70px;
right:100px;
width:200px;
height:200px;
display:none;
z-index:99;
background:url(../images/162.png);
}
WAY 2 is adding is a cancel button like Jared Farrish did here:
http://jsfiddle.net/j4Sj5/4/
if you like his answer, be sure to vot him up below!!
and WAY 3 is what I'm attempting now and should be the most user friendly and flashy. I'll post back once I get it to work correctly!
Ah this is a great one to do yourself. Here's how to do it. First off, live might be overkill for what you need to do. In your case you can use a standard hover event handler in jQuery:
$('#loginButton').hover(function() {
$('#loginBox').fadeIn();
}), function(){
$('#loginBox').fadeOut();
});
The real trick here is that you will trigger the mouse out effect as soon as your mouse moves off the button. This will make the menu disappear when the mouse enters the login box!
So what you actually want to do is handle the hover effect on a containing element. Make sure your #loginButton and #loginBox are contained in a parent element like so:
<div id="loginControl">
<button id="loginButton">Login</button>
<div id="loginBox">...</div>
</div>
Then attach the event to the loginButton's parent:
$('#loginButton').parent().hover(function() { ... }), function(){ ... });
Also, if you are using absolute positioning on #loginBox you'll want to also make sure you use position: relative on it's parent (#loginControl in my example):
#loginControl{ position: relative; }
Let me know if you have any trouble.
Getting More Advanced:
If you want to take this a step further you can try out implementing a simple timeout. I learned early on that it's bad for usability to have a dropdown menu that disappears when I accidentally moved my mouse off the dropdown. To fix this I add a simple delay that prevents the dropdown from hiding if the user's mouse returns to the dropdown within a very short period of time (say 250 to 350ms). I have this as a gist on github in case you want to try it out later: https://gist.github.com/71548
EDIT
(Subsequent EDIT: added a timeout to hide after only a mouseover on the show login element, plus some other updates.)
While I still think using mouseenter and mouseout to handle a login form is not the right way to go from a usability perspective, below is code that demonstrates what Jim Jeffers is describing and attempts to handle some of the pitfalls of the approach:
var setuplogindisplay = function(){
var $loginbox = $('#loginBox'),
$loginshow = $('#loginShow'),
$logincontainer = $('#loginContainer'),
$cancellogin = $('#cancelLogin'),
keeptimeout,
closetimeout;
var keepDisplay = function(){
clearAllTimeouts();
keeptimeout = setTimeout(loginHide, 2000);
};
var loginDisplay = function(){
clearAllTimeouts();
if ($loginbox.is(':hidden')) {
$loginbox.fadeIn();
}
};
var loginHide = function(){
clearAllTimeouts();
if ($loginbox.is(':visible')) {
if (!$(this).is('#cancelLogin')) {
closetimeout = setTimeout(function(){
$loginbox.fadeOut();
}, 1500);
} else {
$loginbox.fadeOut();
}
}
};
function clearAllTimeouts() {
if (keeptimeout) {
clearTimeout(keeptimeout);
}
if (closetimeout) {
clearTimeout(closetimeout);
}
}
$loginshow.mouseover(loginDisplay);
$loginshow.mouseout(keepDisplay);
$logincontainer
.mouseout(loginHide)
.children()
.mouseover(loginDisplay)
.mouseout(keepDisplay);
$cancellogin.click(loginHide);
};
$(document).ready(setuplogindisplay);
http://jsfiddle.net/j4Sj5/19/
Note, you have to make concessions to handle the fact mouseouts will fire when you mouse over elements within the #logincontrol element. I handle this by having them loginDisplay() on mouseenter event (it will work on mouseout, but it makes more logical sense on mouseenter).
I would keep in mind usability of the form when trying to access it and try not to get too clever or over-engineer the user experience. Consider:
<input type="button" id="cancelLogin" value="Cancel" />
Use this to close/hide the form, not an action on another element. If you put the close form action on an event like mouseout, you're going to aggravate your users when they move the mouse accidentally or intentionally out of the way, only to find the login form was closed when they did so. The form, IMO, should have the control which fires the event to hide it according to the user's choice.
<span id="loginButton">Show Login</span>
<div id="loginBox">
<label for="email_B">Email Address</label>
<input type="text" name="email_B" id="email_B" />
<label for="password">Password</label>
<input type="password_B" name="password_B" id="password_B" />
<input type="submit" id="login" value="Sign in" />
<input type="button" id="cancelLogin" value="Cancel" />
<label for="checkbox"><input type="checkbox" id="checkbox" />Remember me</label>
<span>Forgot your password?</span>
</div>
$(document).ready(function(){
var $loginbox = $('#loginBox'),
$button = $('#loginButton'),
$cancellogin = $('#cancelLogin');
var loginDisplay = function(){
$loginbox.fadeIn();
};
var loginHide = function(){
$loginbox.fadeOut();
};
$button.click(loginDisplay);
$cancellogin.click(loginHide);
});
http://jsfiddle.net/j4Sj5/4/
Instead of reinventing the wheel, I would recommend looking into a jquery plugin like hoverintent. It does most of the work for you.
And, on a related note, .live() is being deprecated in jquery as of v1.8. you should instead use .on().
This should work. Plus you don't need live() which by the way is deprecated in favor on on(). You also don't need those functions for a simple fadeIn()/fadeOut():
$('#loginButton').mouseenter(function(){ $('#loginBox').fadeIn(); });
$('#loginBox').mouseout(function(){ $(this).fadeOut(); });

Categories

Resources