function called repeatedly in javascript - javascript

I define a tag picker which will generate checkbox inputs based on "group". If I select the tags I want and press done button, it should return a string to set the value of a text input.
Here are the related codes. The problem is it only works well at the first time. For example, for the first time, if I checked 'jquery','javascript' in the tags,
console.log('output is:' + tags);
print out 'output is: jquery,javascript'. Works!
Then I use it again and select 'jquery','javascript','bootstrap',
it will return
output is: jquery,javascript,bootstrap
output is:
One more time for 'jquery','javascript','bootstrap', it returns
output is: jquery,javascript,bootstrap
output is:
output is:
Seems the done button pressed, the function is called repeatedly. Being stuck with it for several hours but can't figure out. Really appreciate for your answer! Thanks
(function(){
$.fn.tagPicker = function(source,options){
var settings = $.extend({
perRow : 3
},options);
$.fn.attachRow = function(row,col){
//codes here
...
}
$.fn.attachPicker = function(){
//codes here
// generate html for checkbox inputs
...
};
var $input = this;
if($('.tag-picker').length == 0){
$input.attachPicker();
$('body').on('click','.tag-picker .close-picker',function(){
$('.tag-picker').remove();
})
$('.tag-picker .close-picker').off();
$('body').on('click','.tag-picker #btn-done', function(){
var tags = getTags();
$('.tag-picker').remove();
console.log('output is:' + tags);
$input.val(tags);
});
}
function getTags(){
var t = [];
$('.tag-picker input').each(function(){
if($(this).is(':checked')) t.push($(this).attr('id'));
})
return t.join(',');
}
}
})(jQuery);
$('body').on('click','input.participant',function(){
$(this).val('');
$(this).tagPicker(group);
})

You are initialising the plugin every time the elements are clicked. You should initialise it once, on DOM ready.
OR if you want to do this anyway; you could use .one() for the event to run only once and remove itself. Use .off() to detach an event, attached with .on().

Related

Transform String into Array and Select matching words inside the textarea

$('textarea').on('keyup', function(){
var ths = $(this);
var array = $(this).val().split(' ');
array.forEach(function(value){
if (value.match(/(threewords)/g)) {
ths.val().select(value);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>word twowords threewords</textarea>
What I want to do is to select the matching text inside the textarea if it matches the .match(/(threewords)/g) if I wrote word,
The problem is that I keep getting that .match() is null if there is no match or getting select is not a function if the match exists, But nothing is selected and the error occurs, How can I do what i'm trying to do properly?
$('textarea').on('keyup', function(){
var wordToSearch = 'threewords'
var reg = new RegExp('\\b' + wordToSearch + '\\b')
var indexStart = $(this).val().search(reg)
if(indexStart >= 0){
this.selectionStart = indexStart;
this.selectionEnd = indexStart + wordToSearch.length;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>word twowords threewords</textarea>
This code selects threewords if it is written in the textarea.
the match() function returns the matches in an array of strings, i put up an example to demonstrate it easier
try it like this:
$('button').on('click', function(){
console.log('click');
var tarea = $('textarea');
var r = tarea.val().match(/(word)/g);
console.log(r);
console.log('jobs done');
});
try it out on jsfiddle
what else you then want to do depends on what you need, if you just want to know if there is a match you can simply do so by checking if the returned array is empty or not.
in this case i use a button to trigger the check for convenience
edit: version without button jsfiddle
.select doesn't work like you are intending it to.
$("#target").select(value) is incorrect syntax. $("#target").select() is a valid syntax but it does not highlight anything it triggers the select event on an element with id 'target'.
The select event is fired when any text is selected, as in, clicked and dragged over by the mouse. It can be handled by attaching a handler to it:
Example:
$( "#target" ).select(function() {
$( "div" ).text( "Something was selected" ).show().fadeOut( 1000 );
});
ths.val().select(value); part of your code is not a function indeed. Hence the error.
ths.val().select(); on the other hand ends up triggering the select event on the matched value which doesn't serve your purpose.

jQuery nested functions

I am still new to JavaScript and jQuery, so I am confused as to why the following code is not working as I anticipated. All I am trying to do is save input on a button click (id=recordInput) and display it with another button click (id=displayInput). What I observe is that tempInput is stored, (the code works until that point) but assignment of displayInputs onclick attribute is not executed. My question is, can you not nest a $().click() call inside of another &().click() call?
<script>
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
</script>
My thinking is this in pseudocode:
assign recordInput onclick attribute to the following function:
store tempInput
set displayInput onclick to alert the tempInput value
what is wrong with my thinking?
NOTE: I did not include any html tags but all of the ids are referenced correctly
It's not working because you have put & instead of $ here
$('#displayInput').click(function(event) {
Fixing this may work, but you shouldn't set event handlers this way. Because every time your first handler function is called it will set an event handler for the second one. You can try with your console.log and you will see that the number of console.log is increasing by every click on #recordInput. So you should better set it like this :
var tempInput;
$('#recordInput').click(function(event) {
tempInput = $('#testInput').val();
});
$('#displayInput').click(function(event) {
console.log(tempInput);
});
I would change
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
to
$(function(){
var testInput = '';
$('#recordInput').click(function(){
testInput = $('#testInput').val();
});
$('#displayInput').click(function(){
if(testInput !== ''){
console.log(testInput);
}
});
});
You are using & instead of $. Of course, you don't have to format the code exactly like I did.

Jquery $(this).val(); on .ready not working

I'm trying to get the value of a dropdown's option (there is an id on the select markup), when opening the web page
Using
$(document).ready(function() {
$('#cat_list').ready(function(){
var category = $(this).val();
alert(category);
});
});
I get a blank alert.
But Using .change (when selecting something else inside the dropdown) the following code works perfectly with the same function
$(document).ready(function() {
$('#cat_list').change(function(){
var category = $(this).val();
alert(category);
});
});
Finally, this works using basic javascript and it gets successfully the values on open, refresh, on form submit fail, ... etc
$(document).ready(function() {
$('#cat_list').ready(function(){
var e = document.getElementById("cat_list");
var category = e.options[e.selectedIndex].value;
alert(category);
});
});
Thanks for any help on why the first version .ready + $(this).val(); fails
Correct code is:
$(document).ready(function () {
var category = $('#cat_list').val();
alert(category);
});
$(document).ready itself means the whole document (including #cat_list) is ready to be processed. why are you checking if an element is ready or not!!??
you can directly use the value of the element like
$('#cat_list').val();
The documentation says that .ready:
Specify a function to execute when the DOM is fully loaded.
And 3 possible usage cases are:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
However you can actually assign .ready to any element and it will be triggered:
$('#cat_list').ready(function(){
});
This code is fired. BUT this inside .ready function always refers to document.
It will work this way:
$(document).ready(function() {
$('#cat_list').ready(function(){
var category = $('#cat_list').val();
alert(category);
});
});
But actually your code is overengineered:
$(document).ready(function() {
var category = $('#cat_list').val();
alert(category);
});

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Create hidden field element for each drop

I know this is a similar question to my previous one however its slightly different.
I have this script adding each 'dropped' element to a list. Now i need it adding into a variable / hidden field so i can pass it to the next page via a form.
When i run it at the moment. It alerts for each one however, it does it not just for every item dropped but if there are 10 items dropped it will run 10 times per item droped rather than once per item dropped.
Any help would be great.
//Record and add dropped items to list
var txt = $("#listbox");
var dtstart = copiedEventObject.start + '\n'
var caltitle = copiedEventObject.title
var txt = $('#listbox');
txt.append("<li class ='listItem'> "+dtstart +"</li>")
var listItems = $('.listItem');
$('#calendarform').submit(function() {
listItems.each(function(){ //For each event do this:
alert( listItems.text() );
});
return false;
});
// remove the element from the "Draggable Events" list
$(this).remove();
the problem lies in this code
listItems.each(function(){ //For each event do this:
alert( listItems.text() );
});
you are alerting the text of all the list items for each list item.
use jQuery(this) to access the current item within an each block
listItems.each(function(){ //For each event do this:
alert( $(this).text() );
});
Assuming your code is within a drop event handler, you are also adding a submit handler each time you drop. This means that each time you drop, you queue up another submit event. This is probably not desired. Move this submit(function(){}) block outside your drop handler to prevent it from firing that function more than once.
$('#calendarform').submit(function(e) {
var listItems = $('.listItem');
listItems.each(function(){ //For each event do this:
alert( listItems.text() );
});
e.preventDefault();//stop normal behavior
return false;
});
and to create elements on the fly you just pass jQuery the html, and append it to your form.
$('<input type="hidden" name="listItem[]"/>').appendTo("#calendarForm").val(listItem.text())
you may have to fiddle with the name element to get it to submit as an array in your server side language, but you're also within an each loop, which provides you with an index, so you can do the following.
$('#calendarform').submit(function(e) {
var form = $(this);
var listItems = $('.listItem');
listItems.each(function(index){ //For each event do this:
var listItem = $(this);
$("<input type='hidden'/>").val(listItem.text()).appendTo(form).attr('name', 'listItem[' + index + ']');
});
e.preventDefault();//stop normal behavior
return false;
});

Categories

Resources