How can I append the id of a button to an input value on button click?
Example input (buttons pressed):
#en #de #fr #it #es
Example output:
<input name="langs" value="en,de,fr,it,es,">
This is what I have, but it's not working:
$(".lang-btn").click(function() {
$(this).toggleClass("active");
$("input[name=languages]").val() += $(this).attr("id") . ",";
});
I would then like to be able to re-adjust the inputvalue, removing the id, when the button is pressed again.
Close, .val() takes the value as a param:
$(".lang-btn").click(function() {
$(this).toggleClass("active");
var id = this.id,
currentValue = $("input[name=languages]").val();
//Check for existing
if (currentValue.indexOf(id) > -1) {
//remove it
currentValue = currentValue.replace(id + ",", "");
$("input[name=languages]").val(currentValue);
} else {
$("input[name=languages]").val(currentValue + id + ",");
}
});
Working demo: http://jsfiddle.net/9L76d0sr/
If you have radio buttons, you could see if there are checked or not: document.getElementById("X").checked = true;
Then you can append them as you want in your input field
Related
Hi I am developing one jquery application where I have one choosen dropdownlistbox and gridview. The first column of gridview contains checkboxes and at the top it also contains check all button. For example if I check 3 rows inside the gridview then corresponding values in dropdownlistbox i need to disable. I am trying as below.
This is the code to get all the cheked values from gridview.
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true))
{
checkedValues += $(this).val();
}
});
Once i get values in array and when i go to dropdown i have below code.
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
//if (this.value == checkedValues) If this.value is equal to any value from checkedValues then i want to hide that value inside dropdownlistbox.
// Here i want to hide all values of checkedValues array(values will be same in dropdownlistbox)
});
});
I tried as below.
$('.limitedNumbSelect').change(function (e) {
var checkedValues = [];
$("#<%=gdvRegretletter.ClientID %> tr").each(function () {
if ($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true)) {
checkedValues.push($(this).closest('tr').find('td:eq(2)').text().trim());
}
});
$(".limitedNumbSelect > option").each(function () {
var val = $(this).val();
alert(val);
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
$('.limitedNumbSelect option[value=' + display + ']').hide();
$(".limitedNumbSelect").find('option:contains(' + display + ')').remove().end().chosen();
});
});
In above code there is one bug. For example if i select one value from gridview then if i click on dropdown i am able to select that value(on first click). On second click required value will hide.
Above code does not work. Array checkedValues doesnt catch values.
I am unable to figure out what to write inside. Any help would be appreciated. Thank you.
Try something like this:
$('.limitedNumbSelect').change(function (e) {
$("#limitedNumbSelect > option").each(function () {
var val = $(this).val();
var display = checkedValues.indexOf(val) === -1;
$(this).toggle(display);
});
});
Replace the line:
checkedValues += $(this).val();
In this line:
checkedValues.push($(this).val());
I've got a table with a button inside a td, once I press the button it adds text to the td. I want to remove this text inside the td once i press the button again. note that this button is used multiple times in the table hence the class attribute.
Which method could I use to get this done?
This is my code:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<br>" + "test"); // td class="ReleaseTD"
}
// the code above this works
else {
$(this).text("Add");
$('.ReleaseTD').remove("<br>" + "test");
// this obviously is wrong but this is where i would like the correct code
};
});
You could create ID for text inside like this:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<span id='textID'><br>" + "test</span>");
}
else {
$(this).text("Add");
$('#textID').remove();
};
});
Please try the following:
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
var label = $(this).text();
if (label == "Add") { // it is "Add" by default
$(this).text("Cancel");
$('.ReleaseTD').append("<span id='txt_name'><br>" + "test</span>");
}
// the code above this works
else {
$(this).text("Add");
$('#txt_name').remove();
};
});
Two ways:
1) Append your text into a span with a unique ID, and then delete this ID. For example, delete the ID with the largest number. Dumbest way would be to just store the latest ID in a global variable.
var global_last_appended_id = 0;
$(document).on('click', '.releasebutton', function () { // button class="releasebutton"
global_last_appended_id ++;
$('.ReleaseTD').append("<span id='appended-text-" + global_last_appended_id + "'><br>" + "test</span>");
}
// the code above this works
else {
$(this).text("Add");
$('#appended-text-' + global_last_appended_id).remove();
global_last_appended_id--; //go one step back so next time we remove the previous paragraph
};
});
Update: after your edit I've added the ability to undo multiple times. Basically there is unlimited undo.
2) [lame and wrong] Save the previous .html() - the whole HTML code of your element - into a global variable; then restore the previous version of the text from the global variable when necessary.
I am trying to build somewhat of a fee voucher with jquery and I am having a heck of a time figuring out how to go about making it all work.
I want when I select option js input field id fee-2 will disable and when I select option php input field id fee-1 will disable and so on more rows inserted for different from select option on different rows. at last need some of all rows inserted by field id fee-1 and fee-2 separately both
My Fiddle Demo is
http://fiddle.jshell.net/softfiddle/cSbbK/2/
thanks
$("#mytable").on("change", "select", function () {
var getSelectValue = $(this).val();
if (getSelectValue == 1) {
$(this).parents('td').next().find('#fee-2').prop('disabled', true);
$(this).parents('td').next().next().find('#fee-1').prop('disabled', false);
} else {
$(this).parents('td').next().find('#fee-2').prop('disabled', false);
$(this).parents('td').next().next().find('#fee-1').prop('disabled', true);
}
});
JSFIDDLE
Updated: Have added two classes to the textbox .i.e fee_course_1,fee_course_2 so we can loop over it and get sum values
$("#calsum").click(function () {
var sum_fee_1 = 0;
var sum_fee_2 = 0;
$('.fee_course_1').each(function () {
sum_fee_1 += Number($(this).val());
});
$('.fee_course_2').each(function () {
sum_fee_2 += Number($(this).val());
});
alert("Fee_1 = " + sum_fee_1 + " and Fee_2 = " + sum_fee_2);
});
JS FIDDLE DEMO 2
I've written a custom form validation script, but for some reason, wrapping input[type=text] elements in <div class="inputWrapper" /> stops me from preventing input[type=submit]'s default setting.
Here's the relevant code:
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
Is breaking:
$("input[type=submit]").click(function(event) {
event.preventDefault();
});
Why is this happening? If you need a more full script, let me know, and I'll just post the whole thing.
Alright, so for some reason, disabling that line of code allows .preventDefault on the input[type=submit] to work, but if I just use
// wrap inputs
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
// validate on form submit
$("input[type=submit]").click(function(event) {
event.preventDefault();
});
It works fine. So here's the full script, what could cause this weirdness?
$(document).ready(function() {
// wrap inputs
$("input[type=text]").wrap("<div class=\"inputWrapper\" />");
$("textarea").wrap("<div class=\"inputWrapper\" />");
// validate text inputs on un-focus
$("input[type=text].required").blur(function() {
if ($(this).hasClass("error")) {
// do nothing
} else if ($(this).val() === "") {
$(this).addClass("error");
$(this).parent(".inputWrapper").append("<div class=\"errorPopup\">" + $(this).attr("placeholder") + "</div>");
}
});
// validate textareas on un-focus
$("textarea.required").blur(function() {
if ($(this).hasClass("error")) {
// do nothing
} else if ($(this).val() === "") {
$(this).addClass("error");
$(this).parent(".inputWrapper").append("<div class=\"errorPopup\">" + $(this).attr("placeholder") + "</div>");
}
});
// validate on form submit
$("input[type=submit]").click(function(event) {
event.preventDefault();
// check fields
$(this).parent("form").children("input.required").each(function() {
// check textboxes
if ($(this + "[type=text]")) {
if (!$(this).val()) {
$(this).addClass("error");
};
};
// end textboxes
// check textareas
$(this).parent("form").children("textarea.required").each(function() {
if (!$(this).val()) {
$(this).addClass("error");
};
});
// end textareas
// check checkboxes and radio buttons
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var inputName = $(this).attr("name");
if (!$("input[name=" + inputName + "]").is(":checked")) {
var inputId = $(this).attr("id");
$("label[for=" + inputId + "]").addClass("error");
};
};
// end checkboxes and radio buttons
});
// end fields
// submit form
var errorCheck = $(this).parent("form").children(".error").length > 0;
if (errorCheck == 0) {
$(this).parent("form").submit();
} else {
alert("You didn't fill out one or more fields. Please review the form.");
window.location = "#top";
};
// end submit form
});
// clear errors
$("input.required").each(function() {
// clear textboxes
if ($(this + "[type=text]")) {
$(this).keypress(function() {
$(this).removeClass("error");
$(this).next(".errorPopup").remove();
});
};
// end textboxes
// clear textareas
$("textarea.required").each(function() {
$(this).keypress(function() {
$(this).removeClass("error");
$(this).next(".errorPopup").remove();
});
});
// end textareas
// check checkboxes and radio buttons
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var inputName = $(this).attr("name");
var labelFor = $(this).attr("id");
$(this).click(function() {
$("input[name=" + inputName + "]").each(function() {
var labelFor = $(this).attr("id");
$("label[for=" + labelFor + "]").removeClass("error");
});
});
};
// end checkboxes and radio buttons
});
// end clear textbox errors
});
Alright, I was wrong about what the problem was. It's related to the line I thought it was, but it's actually having an issue finding the .error after I wrap the inputs.
Here's where the problem lies:
var errorCheck = $(this).parent("form").children(".error").length > 0;`\
var errorCheck = $(this).parent("form").children(".error").length > 0;
When you .wrap the text inputs, they are no longer children of the form. Use .find
By the way, $(this + "selector") is not valid. You probably want to use $(this).is("selector")
You will need some sort of reference maintained with the new DOM element. This would be placing it as an initialised DOM element in a variable first (not as a string as you did) and the same for the original element, which will be placed back in to maintain the event:
var $inputWrapper = $("<div class=\"inputWrapper\" />"),
$inputText = $("input[type=text]");
$inputText.wrap("<div class=\"inputWrapper\" />");
Then you can replace the element back in.
I have a bunch of radio buttons that are below. These radio buttons are part of a larger form and are optional, so If a user clicks on one, then decides he/she doesn't want the option selected, there is no way to undo this.
I was wondering if there was any jQuery etc, that, when clicking a link for example, clear any radio selection, based on the group name in the HTML?
Thanks
var group_name = "the_group_name";
// if jquery 1.6++
$(":radio[name='" + group_name + "']").prop('checked', false);
// prev than 1.6
// $(":radio[name='" + group_name + "']").attr('checked', false);
Working demo: http://jsfiddle.net/roberkules/66FYL/
var Custom = {
init: function() {
checkAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and click it
$(container).find('input[type=checkbox]:not(:checked)').each(function(){
if($.browser.msie){
$(this).attr('checked','checked');
}else{
$(this).trigger('click');
};
});
};
uncheckAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and unselect them
$(container).find('input[type=checkbox]:checked').each(function(){
$('label[for="'+$(this).attr('id')+'"]').trigger('click');
if($.browser.msie){
$(this).attr('checked','');
}else{
$(this).trigger('click');
};
});
};
I have created it in an init function, and adter then i called the init.
}
window.onload = Custom.init;
I have created a solution like roberkules' solution, except mine clears the radiobutton if you click the radiobutton itself while it's checked. Use this if you don't want to add an extra "Clear" button to your layout.
http://jsfiddle.net/P9zZQ/6/
// Requires JQuery 1.4+ (possibly earlier)
$(function () {
// Turn off a radiobutton if clicked again while on
var checkOff = function (event) {
var target = $(event.target);
if (target.is('label')) {
// deal with clicked label
if (target.attr('for')) {
// label has 'for' attribute
target = $('#' + target.attr('for'));
} else {
// label contains a radiobutton as a child
target = target.find('input[type=radio]');
}
}
if (target.is('input:checked[type=radio]')) {
event.preventDefault();
window.setTimeout(function () {
target.attr('checked', false);
}, 200);
}
}
// Find all radiobuttons and labels inside .radio-clearable containers
$(
'.radio-clearable input[type=radio], ' +
'.radio-clearable label').mousedown(function (event) {
// When clicked -- clear if it was checked
checkOff(event);
}).keydown(function (event) {
// When receiving space, escape, enter, del, or bksp -- clear if it was checked
if (event.which == 32 || event.which == 27 || event.which == 13 || which == 46 || which == 8) {
checkOff(event);
}
});
});
Usage: For any radiobutton you want to be clearable in this manner, wrap it in a container with class "radio-clearable".
The code is triggered by clicking or sending a key (Space, Escape, Enter, Del, BkSp) to the radiobutton element or to its label.