Working version http://jsfiddle.net/uxBZN/
Would it be better to just replace password or text within the type (type="password") parameter of html input tag, instead of the whole html input type tag, as seen below?
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$("#security_answer").replaceWith('<input type="text" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="text" name="hnumber" value="'+hnumber+'" id="hnumber">');
} else {
$("#security_answer").replaceWith('<input type="password" name="answer" value="'+security_answer+'" id="security_answer">');
$("#hnumber").replaceWith('<input type="password" name="hnumber" value="'+hnumber+'" id="hnumber">');
}
});
This needs to work with IE 7/8 and I want to retain the currently entered text.
Yes, you can do that.
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
var type = $(this).is(':checked') ? "text" : "password";
$("#security_answer").replaceWith('<input type="' + type + '" name="answer" value="'+security_answer+'" id="security_answer" />');
$("#hnumber").replaceWith('<input type="' + type + '" name="hnumber" value="'+hnumber+'" id="hnumber" />');
});
Note: Inside the handler you can use this to refer to #unhide_typing and also if you are using jQuery ver 1.7+ then it is preferrable to use on instead of live.
Replacing some properties of HTML elements with jQuery could be tricky on older versions. I recommend you to stay with .prop() function and do not replace DOM elements.
So, your code should be this:
$("#unhide_typing").live("click", function(){
var security_answer = $("#security_answer").val();
var hnumber = $("#hnumber").val();
if ($('#unhide_typing').is(':checked')) {
$('#security_answer').prop('type', 'text');
$('#hnumber').prop('type', 'text');
} else {
$('#security_answer').prop('type', 'password');
$('#hnumber').prop('type', 'password');
}
});
Yes, it's better to just replace the type for a number of reasons:
Better performance (an element isn't getting removed and then a new one getting created/inserted into the DOM)
Doesn't break the browser's built-in undo mechanism (probably not critical for this use-case, but perhaps it is in others).
Any other event handlers bound to the original input won't get removed
Just make sure you use jQuery's .prop() method rather than .attr():
http://jsfiddle.net/uxBZN/2/
Related
I am trying to replace a div with another div onclick using the code below. It works fine for one instance. However, the problem is when the class appear more than once which is the case for me (multiple instances)it obviously changes all instance as they have the same class name.
Is there a way to make it only change the clicked instance? Thanks
HTML
<div id="test"></div>
JavaScript (dynamically creating HTML)
var html =
'<form action="test.php" method="get" class="myForm">' +
'<input type="hidden" name="mID" value="' + this.id + '"/>' +
'<input type="image" class="send" src="this.image" name ="send" alt="submit"/>' +
'</form>';
$('div#test').append(html);
$("#test").on('click', '.send', function(e) {
e.preventDefault();
var $form = $(this).closest('form');
$.get($form.attr("action"),
$form.find(":input").serializeArray(),
function(data) {
$('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
});
});
$("#test").on('submit', '.myForm', function(e) {
return false;
});
SOLUTION;
Instead of;
$('.myForm').replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
CORRECT WAY;
$form.replaceWith('<div class="myForm2"><img src="Icons/PNG/tick 2.png" alt="submit"/></div></div>');
You're already most of the way there with $form = $(this).closest('form'); but for some reason you started selected all the forms instead by using $('.myForm'), so
replace
$('.myForm').replaceWith(...
with
$form.replaceWith(...
First of all, you are not replacing a div, you are replacing a form (with class .myForm). As this form is inside the div you are clicking on when you want to change your form you could use:
$(this).find(".myForm").replaceWith...
$(".targetClass").click(function(){
var theDivBeingClicked = $(this);
//Do something
})
Simple!
I am no JQuery Expert, but we doit the traditional way!
var elements = document.getElementByID('test')
we would have elemements[0] and elements[1] .... everything with the id="test" inside. but only the first element needs to be replaces.
so, our choice falls on elements[0].
$('.myForm').replaceWith(.....)
take myForm away, and add the elements array number you'd like having to be replaces, then it's always this element in the doc that is being replaces.
have fun!
I'm trying to put together multiple user inputs and then combine them into one textarea after button click.
For example:
User1:Hey, I just met you
User2:And this is crazy
User3:But Here's my number so call me maybe
Combined Result:
Hey, I just met you, And this is crazy, But Here's my number so call me maybe
Here's my code the button click is currently not working but when I tried it before it did work so I was thinking I have some problem w/ my Jquery that triggers this unusual result:
HTML and Imports:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input class="combine" id="input1" disabled="true"></input>
<input class="combine" id="input2" disabled="true"></input>
<input class="combine" id="input3" disabled="true"></input>
<input class="combine" id="input4" disabled="true"></input>
<input class="combine" id="input5" disabled="true"></input>
<input class="combine" id="input6" disabled="true"></input>
<input class="combine" id="Voltes5" disabled="true" size="45"></input>
<button id="setVal">Set</button>
Jquery
$(document).ready(function(){
$('#setVal').on('click',function(){
jQuery(function(){
var form = $('.combine');
form.each(function(){
$('.Voltes5').append($(this).text()+ ' ');
});
});
});
});
Update for sir Arun P Johny
User1: If theres a (no comma when combined)
User2: will
User3: there's a way
Combined Result:
If theres a will, there's a way
Try
$(document).ready(function () {
$('#setVal').on('click', function () {
var form = $('.combine').not('#Voltes5');
var vals = form.map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
$('#Voltes5').val(vals.join(', '))
});
});
Demo: Fiddle
Here's a one-liner for non-readability ;)
$('#setVal').click(function(){$('#Voltes5').val($('.combine').not('#Voltes5').map(function(){return $(this).val();}).get().join(''))});
Expanded:
$('#setVal').click(function(){
$('#Voltes5').val(
$('.combine')
.not('#Voltes5')
.map(
function(){
return $(this).val();
})
.get()
.join('')
);
});
Get fiddly with it: http://jsfiddle.net/ArtBIT/u57Zp/
Here is one way to do this:
$('#setVal').on('click', function () {
$(".combine[id^=input]").each(function () {
if(this.value) {
$("#Voltes5")[0].value += ' ' + this.value;
}
});
});
There are several different ways to do this..
I'd do it this way using an array:
$(document).ready(function () {
$('#setVal').on('click', function () {
//create an array for the values
var inpAry = [];
$('.combine').each(function () {
//add each value to the array
inpAry.push($(this).val+' ');
});
//set the final input val
$('#Voltes5').val(inpAry);
});
});
but you would need to remove the combine class from #setVal because that would be included in the .each.
This way it would also be possible to have the final box updated on keyup as I'm not just appending the values, the combined values are set each time.
$(document).ready(function(){
$('#setVal').on('click',function(){
var val='';
$('.combine').not('#Voltes5').each(function(){
val+=$(this).val();
});
$('#Voltes5').val(val);
});
});
.text() will give text of the element ,for input val u have to use .val()
So there's immediate big problem in the code, which is that you're referring to your Voltes5 element as a class, not an ID. The jQuery selector you want is:
#Voltes5
instead of:
.Voltes5
There are a few other things to think about too, though, for the sake of functionality and best practices. Firstly, the Voltes5 element also has class combine, meaning that the $('.combine').each() call will include this element. The outcome of this is that it will also append its current text to itself when the code is run (or, when the code is run with the above correction).
When grabbing the current entered text of an input element, a jQuery .val() call is what you want, not .text() - see this answer for some more discussion.
Another thing that could be noted is that you should really explicitly specify what sort of input these elements are; <input type="text"> is hugely preferable to <input>.
Finally, input is a void element (reading), meaning it shouldn't have any content between opening and closing tags. Ideally, you wouldn't even give a closing tag; either have just the opening tag, or self-close it:
<input>
<input />
HTH
replace $('.Voltes5').append($(this).text()+ ' ');
with
$('#Voltes5').append($(this).text()+ ' ');
I am trying to make a counter for "Number of characters left" in a form:
<input type="text" id='username_input'>
<input type="text" id='password_input'>
Is it possible to make a function whose parameter will be part of the selector?
So you can understand my question better, I'll show you an example that I did, and that doesn't work.
What I'm trying to do will seem obvious. This implies I have to standardize all id's.
I'm aware I could make a maxChar parameter in the function, but I left my mistake field+'_maxChar' so that you can tell me why it's not possible.
THanks a lot in advance
var username_maxChar=20,password_maxChar=30;
function countLeft(field,minCharacters){
$('#'+field+'_input').keyup(function(){
var input_length = $('#'+field+'_input').val().length;
var input_count = field+'_maxChar' - input_length;
$('#'+field+'_counter').text(input_count);
});
}
countLeft(username,6);
Since you have defined these with the var keyword outside the function scope, they become properties of the window object and can be accessed with the [] notation:
var input_count = window[field + '_maxChar'] - input_length;
However, you might consider just using the maxlength attribute:
<input type="text" id='username_input' maxlength='20'>
<input type="text" id='password_input' maxlength='30'>
These are available to jQuery via .attr()
var input_count = $('#' + field + '_input').attr('maxlength') - input.length;
In this example
<form id="form1">
<input type="text" name="style">
</form>
<form id="form2">
<input type="text" name="id">
</form>
you cannot access form1's style declaration or form2's id, since the named inputs shadow the corresponding properties.
The same holds for other properties too
Any workarounds?
Edit:
getAttribute works for id, obviously. But not for style, childNodes, tagName etc.
I'm looking for something like this:
getDomProp = (function() {
if (window.__lookupGetter__) {
var cleanForm = document.createElement('form');
return function(form, key) {
// works in Firefox, fails in Opera:
return cleanForm.__lookupGetter__(key).call(form);
};
} else if (Object.getOwnPropertyDescriptor) {
return function(form, key) {
// does not work at all:
// return Object.getOwnPropertyDescriptor(cleanForm, key).get.call(form);
}
} else {
throw 'Not supported.';
}
})();
Fiddle
This will still work:
form.getAttribute('id');
PS. Don't name your inputs that in production code :)
Use getAttribute to get the corresponding form attributes: http://jsfiddle.net/6d8sx/3/
alert('id: ' + form.getAttribute('id'));
Edit: getAttribute seems to work in IE9, FF5 (not sure about others).
However, naming your elements that way will cause problems down the line (if not your code, then some library or plugin might get confused).
Access them using .getAttribute();
http://reference.sitepoint.com/javascript/Element/getAttribute
yuse jquery: $('#form1').css(), or $('#form2').attr('id').
I want to know if its possible to change the name of the input tag with javascript or jquery, for example in this code :
<input type="radio" name="some_name" value="">
I want to change the some_name value when user select this radio button.
the reason what i want to do this is described here : How might I calculate the sum of radio button values using jQuery?
Simply elem.name = "some other name" or elem.setAttribute("name", "some other name") where elem is the element you want to alter.
And to do that on selection, use the onchange event:
<input type="radio" name="some_name" value="" onchange="if(this.selected) this.name='some other name'">
And to apply that behavior to every radio button with that name:
var inputElems = document.getElementsByTagName("input");
for (var i=inputElems.length-1; i>=0; --i) {
var elem = inputElems[i];
if ((elem.type || "").toLowerCase() == "radio" && elem.name == "some_name") {
elem.onchange = function() {
if (this.selected) {
this.name = "some other name";
}
};
}
}
But using jQuery for that is quite easier.
The jQuery way
$('input:radio[name="some_name"]').attr('name', 'new name');
Gumbo has the vanilla JavaScript way covered
Yes, you can change the name of any element with javascript. Keep in mind though that IE 6 and 7 have trouble with submitted forms where the input elements have been tinkered with in javascript (not sure if this exact case would be affected).
$('input:radio[name="some_name"]').attr('name', 'new_name');
Edit: To change it only when it is selected, here is the code for that:
$("input:radio[name='some_name']").click(function() {
if ($(this).attr('checked')) $("input:radio[name='some_name']").attr('name', 'new_name');
else $("input:radio[name='some_name']").attr('name', 'some_name');
});
Sure. If jQuery is your poison, this should do the trick:
$("input[name=some_name]").attr("name", "other_name");
I came up with this:
<input type="radio" name="some_name" value="" id="radios">
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#radios").click(function()
{
$(this).attr("name", "other_name");
});
});
</script>
Trying to change the name attribute of a radio button will cause strange, undesirable behavior in IE.
The best way to handle this is to replace the old radio button with a new one. This post may help you. If you are using jQuery, you can do it with the replaceWith function.
More information about changing name attributes in IE.