jquery return value of input to var - javascript

I'm trying to make a variable equal the value of the text box. I have the text box value being set to a variable and returned as an alert (for now) but I can't figure out how to call that variable from other functions.
$('#max_char').keyup(function () {
var max_char = $(this).val();
alert(max_char + ' Handler for .keyup() called.');
});
var count_options = {
'maxCharacterSize': max_char,
'originalStyle': 'originalDisplayInfo',
'warningStyle': 'warningDisplayInfo',
'warningNumber': 40,
'displayFormat': '#input Characters | #left Characters Left | #words Words'
};
$('#textinput').textareaCount(count_options);
});
HTML
<textarea cols="68" rows="21" name="textinput" id="textinput"></textarea><br/>
<input type="textbox" id="max_char" name="max_char" value="-1" /> Max Characters <br/>
Any help would be great. Trying to add the var max_char to the maxCharacterSize of count_options

All you need to do is declare max_char in a higher scope, i.e. outside of the keyup function:
var max_char;
$('#max_char').keyup(function () {
max_char = +$(this).val();
alert(max_char + ' Handler for .keyup() called.');
});
Also note that I put a + in front of $(this).val() to convert it from a string into a number, since "1" + 1 == "11".
Update:
The reason the textareaCount plugin isn't working is because it is initialised once, on document ready. At this time, max_char is nothing because the user hasn't typed anything yet.
You'd have to either reconfigure or re-initialise the plugin on every keyup to get the effect you're after. Unfortunately the plugin doesn't document an easy way to do this. After digging through the plugin's source code, I think there are only 3 events it binds that you need to revert, before you can simply re-initialize it again. Try this out:
var count_options = {
'maxCharacterSize': 100, // Just some default value
'originalStyle': 'originalDisplayInfo',
'warningStyle': 'warningDisplayInfo',
'warningNumber': 40,
'displayFormat': '#input Characters | #left Characters Left | #words Words'
};
// Initialise the plugin on document ready
$('#textinput').textareaCount(count_options);
$('#max_char').keyup(function () {
var max_char = +$(this).val();
count_options.maxCharacterSize = max_char;
// Unbind the 3 events the plugin uses before initialising it
$('#textinput')
.next('.charleft').remove().end()
.unbind('keyup').unbind('mouseover').unbind('paste')
.textareaCount(count_options);
});

If I understand you correctly, if you declare the var within the global scope of javascript
Or if you directly access the input with
$("#max_char").val()

parseInt($('#max_char').val())

Related

Firing javascript on multiple ids

My coffee script gets launched through this line:
$(document).on 'change', '#myid1'
Now it should also get launched on changes of
'#myid2'
'#myid3'
'#myid4'
.
.
.
And so on..
And it should also remember the number that launched the script. For example if #myid1 gets changed the javascript should get fired and save the "1".
How do i do that?
Best regards!
Is this what you are looking for?
Code :
$(document).on('change', '#myid1, #myid3, #myid4', function () {
var id = $(this).attr('id');
var num = id.substring(id.length - 1, id.length);
alert(num); // Should alert the correct value (1, 3, 4 etc...)
});
You may also want to look at adding a class to each element (i.e. <input type="text" class="inputElem" id="myid1" />
And then change to code to handle changes based on this class instead of listing the Ids :
$(document).on('change', '.inputElem', function () {
var id = $(this).attr('id');
var num = id.substring(id.length - 1, id.length);
alert(num); // Should alert the correct value (1, 3, 4 etc...)
});

plus minus button with specific parent input doesn't work

as you can see here jsfiddle.net/TTU4Z/1/
The jquery code in question is below and if i run it without all my code (like in jsfiddle) it run perfectly. but with all my code doesn't run.
$(document).ready(function() {
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[id='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
});
// This button will decrement the value till 1
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
});
});
Clicking on "add" button all is good, but when you click in one of minus or plus button it delete all.
It should increase or decrease the val of the relative input as you can see, but nothing change if i try to edit everything in those functions.
What to do?
Since you are appending elements dynamically you have to use event delegation in this situation. Actually the registered events are not invoking in your context, that's why the buttons are exhibiting their original behavior.
Try,
$(document).on('click','.plus',function(e){
and
$(document).on('click','.minus',function(e){
Additionally, the selector that you are framing dynamically contains some meta-characters, just pass that as a string or you have to escape it, in order to make your code work properly.
DEMO
New Demo after fixing your concatenation issues. And in that demo, i just removed the attribute selectors like [id='blah'] and replaced that with $('#blah').
DEMO - I
See updated fiddle http://jsfiddle.net/LfNmh/
You had your x variable inside the code string where it should have been in the code. line 15 ..
var numPortata = '<td><button class="minus" field="portata'+x+'">-</button><input id="portata'+x+'" type="number" name="numPortata[]" value="1" size="10" min="1" max="10" step="1" required><button class="plus" field="portata'+x+'">+</button></td>';
I also changed the code so that the events are attached at the document level as Rajaprabhu said.

Optimizing code to define variables only once, code only works when the vars are in change function and for the code outside change I redefine?

Pretty sure I know the solution... would write .on('change','load', function(){}
correct? <-- Tested didn't work? so I am up to your solutions :)
Sushanth -- && adeneo both came up with great solutions, this is a good lesson in optimizing code... It's gonna be hard to choose which answer to go with, but I know this is going to help me rethink how I write... I dont know what I do without this forum, id have to learn this stuff in college.
This is purely a question out of curiosity and bettering my skills, as well as giving you guys a chance to display your knowledge on jQuery. Also to prevent any sloppy writing.
I have a radio based switch box, the markup looks like this, the id's and on/off values are generated by the values in my array with PHP...
<span class="toggle-bg">//This color is the background of the toggle, I need jQuery to change this color based on the state on/off
<input type="radio" value="on" id="_moon_page_header_area1" name="_moon_page_header_area">//this is my on value generated by the array
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">// I create this input because I have multiple checkboxes that have the ID _moon_ARRAYVALUE_area1
<input type="radio" value="off" id="_moon_page_header_area2" name="_moon_page_header_area">// off value
<input type="hidden" value="_moon_page_header_area" class="switch-id-value">//_moon_ARRAYVALUE_area2
<span class="switch"></span>// the switch button that changes
</span>
Hope that makes sense and the comments are clear
Here is the jQuery
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.hide()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.show()
}
$('.toggle-bg').change(function () {
var value = $('.toggle-bg input.switch-id-value').val()
var moon1 = $('#'+value+'1').is(':checked');
var moon2 = $('#'+value+'2').is(':checked');
var static_slide = $('._moon_staticarea_height');
var toggle = $('.toggle-bg');
if(moon1){
toggle.css({'background-color': '#46b692'});
static_slide.slideUp()
} else
if (moon2){
toggle.css({'background-color': '#333'});
static_slide.slideDown()
}
});
it looks longer than it really is, its just repeating it self, one is on load so that it gives the correct color on load of the page, and then inside the change function we need to change colors..
How do I write it so I only have to use variables one time (so its cleaner) is there a better way to optimize it... Just NOW thinking after writing this I could put it in one function .on('load', 'change', function() {}
I just now thought of that, but I wrote all this so I am going to see what others think...
You'd do that by having the function in the change event handler, and on the end you chain on a trigger('change') to make it work on pageload :
$('.toggle-bg').on('change', function () {
var value = $('.toggle-bg input.switch-id-value').val(),
moon1 = $('#' + value + '1').is(':checked'),
slider = $('._moon_staticarea_height'),
toggle = $('.toggle-bg');
toggle.css('background-color', (moon1 ? '#46b692' : '#333'));
slider[moon1?'slideUp':'slideDown']();
}).trigger('change');
As radiobuttons can't be unchecked, it's either moon1 or moon2, which means checking one of them should be enough.
.on('change','load',
supposed to be
// Remove the comma separator if you want to bind the same handler to
// multiple events.
.on('change load',
And you can remove the one separately written out and enclose it in a function (if multiple instances of the class toggle-bg)
or just trigger the change event.(If there is a single instance of a class)
This will just run the same functionality when the page loads.
var toggle = $('.toggle-bg');
toggle.change(function () {
var value = $('input.switch-id-value', this).val(),
moon1 = $('#' + value + '1').is(':checked'),
moon2 = $('#' + value + '2').is(':checked'),
static_slide = $('._moon_staticarea_height');
if (moon1) {
toggle.css({
'background-color': '#46b692'
});
static_slide.slideUp()
} else if (moon2) {
toggle.css({
'background-color': '#333'
});
static_slide.slideDown()
}
}).change();

Special HTML characters injected with JS

I have a button (named Benjamin):
<input type="submit" name="btn_submit" value="Next →" />
And on a click event it says 'Loading' and does cool stuff. However, if there is a problem, I want it to change back to its original text while displaying the error message elsewhere.
$('input[name=btn_submit]').click(function() {
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val('Next →');
return false;
});
Somehow, the literal text → is applied to the button, rather than the cool →. How do I fix this?
Html is evaluated with different rules that JavaScript is. Html entities only parsed by the html parser. Either use the unicode literal, like so:
$(this).val('Next \u2192');
Or better, keep track of the original value and then set it back:
var initalButtonValue = $(this).val();
$(this).val('Loading');
// Stuff
$(this).val(initialButtonValue);
Or perhaps even better, use HTML data attributes to store the states.
<input type="submit" name="btn_submit" value="Next →" data-normal-value='Next →' data-loading-value='Loading...' />
Then:
// Set to loading
$(this).val($(this).data("loading-value"));
// and back to normal
$(this).val($(this).data("normal-value"));
Put the actual → character in there instead of a HTML entity. Using an entity only works if you set HTML content - and form values are not HTML at all.
When using it inside <input value="..."> it only works because in this case the entity is replaced while the HTML is parsed, so the value gets the actual character.
How about storing the value of the element with $.data() and retrieving it later:
$('input[name=btn_submit]').click(function() {
$.data(this, 'value', this.value);
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val($.data(this, 'value'));
return false;
});
Here is a demo: http://jsfiddle.net/39thm/ (the setTimeout is just for demonstration)
Docs for $.data(): http://api.jquery.com/jquery.data
Also you are using thr $(this) selector more than once, if you use it a bunch then it's a good idea to cache the selection:
$('input[name=btn_submit]').click(function() {
var $this = $(this);
$.data(this, 'value', this.value);
$this.val('Loading');
// Logicy Stuff...
// Error?
$this.val($.data(this, 'value'));
return false;
});
if you know the code for the character, you can add it to a JavaScript string with .fromCharCode():
var s = "hello " + String.fromCharCode(1023); // just a made-up number
You can also embed characters in JavaScript strings if you know their hex code:
var s = "string \u1023 string";
$("input[name='btn_submit']").click(function() {
var elem = $(this);
elem.data( "orgText", elem.val() ).val('Loading');
window.setTimeout(
function(){
elem.val( elem.data("orgText") );
}, 1000 );
return false;
});​
jsFiddle

Calling a jQuery method at declaration time, and then onEvent

I've been writing JS (mainly jQuery) for quite a few months now, but today I decided to make my first abstraction as a jQuery method. I already have working code but I feel/know that I'm not doing it the right way, so I come here for some enlightenment.
Note: Please do not reply that there's already something out there that does the trick as I already know that. My interest in this matter is rather educational.
What my code is intended to do (and does):
Limit the characters of a textfield and change the color of the counter when the user is approaching the end.
And here's what I have:
$(function(){
$('#bio textarea').keyup(function(){
$(this).char_length_validation({
maxlength: 500,
warning: 50,
validationSelector: '#bio .note'
})
})
$('#bio textarea').trigger('keyup');
})
jQuery.fn.char_length_validation = function(opts){
chars_left = opts.maxlength - this.val().length;
if(chars_left >= 0){
$(opts.validationSelector + ' .value').text(chars_left);
if(chars_left < opts.warning){
$(opts.validationSelector).addClass('invalid');
}
else{
$(opts.validationSelector).removeClass('invalid');
}
}
else{
this.value = this.value.substring(0, opts.maxlength);
}
}
In the HTML:
<div id="bio">
<textarea>Some text</textarea>
<p class="note>
<span class="value">XX</span>
<span> characters left</span>
</p>
</div>
Particularly I feel really uncomfortable binding the event each on each keyup instead of binding once and calling a method later.
Also, (and hence the title) I need to call the method initially (when the page renders) and then every time the user inputs a character.
Thanks in advance for your time :)
chars_left is a global variable which is not good at all. Here is a better (slightly changed) version:
jQuery.fn.char_length_validation = function(opts) {
this.each(function() {
var chars_left = opts.maxlength - $(this).val().length;
$(this).keyup(function() {
chars_left = opts.maxlength - $(this).val().length;
if (chars_left >= 0) {
$(opts.validationSelector).text(chars_left);
if (chars_left < opts.warning) {
$(opts.validationSelector).addClass('invalid');
}
else {
$(opts.validationSelector).removeClass('invalid');
}
}
else {
$(this).val($(this).val().substring(0, opts.maxlength));
}
});
});
this.keyup(); // makes the "initial" execution
return this;
};
See a DEMO.
Some explanation:
In a jQuery plugin in function, this refers to the elements selected by the selector. You should use this.each() to loop over all of these and set up every element accordingly.
In this example, every element gets its on chars_left variable. The event handler passed to keyup() has access to it as it is a closure. Update: It is already very late here ;) It is not necessary to declare it here as you recompute the value every time anyway. Still, it should give you an idea how to have private variables that persist over time.
You should always return this to support chaining.
Further thoughts:
You might want to think about how you could make it work for several textareas (i.e. you have to think about the validation selector). Don't tie it to a specific structure.
You should have default options.
Update: Of course you can make your plugin work with only one textarea (like some jQuery functions work).
You can do the binding and initial triggering in the method:
jQuery.fn.charLengthValidation = function(opts) {
return this.keyup(function() {
var charsLeft = opts.maxLength - $(this).val().length;
if (charsLeft >= 0) {
$(opts.validationSelector + ' .value').text(charsLeft);
$(opts.validationSelector).toggleClass('invalid', charsLeft < opts.warning);
} else {
$(this).val($(this).val().substring(0, opts.maxLength));
}
}).trigger('keyup');
}
$(function() {
$('#bio textarea').charLengthValidation({
maxLength: 25,
warning: 10,
validationSelector: '#bio .note'
});
});

Categories

Resources