How to append and remove checkbox values to and from hidden field - javascript

I am trying to append selected checkbox values to the hidden field.
But I am only successfull in adding only one checkbox value at this time.
Is there anyway to append selected checkbox values in hidden field.
function CheckBox_Clicked(item) {
if (item.checked == true) {
$('#Chkboxvalue').val($(item).val());
}
}
I don't know if I could use jquery append function here.
Thanks

Please use below javascript
function CallOnEachCheckBoxChangeEvent(){
var selectedCheckBoxesValue = '';
$('#DIVID').find("input:checkbox.CheckBoxClassName:checked").each(function (i, selected) {
if (selectedCheckBoxesValue.length == 0) {
selectedCheckBoxesValue += $(selected).val();
}
else {
selectedCheckBoxesValue += ',' + $(selected).val();
}});
//Set the value of hiddenField selected checkboxes value
$(hiddenFieldValueId).val(selectedCheckBoxesValue);
}

$('#Chkboxvalue').val($('#Chkboxvalue').val()+' '+$(item).val());

There is an easier way to do that.
$('input[type="checkbox"]:checked').map(function() {
return $(this).val();
}).get().join();
Demo : http://jsfiddle.net/codef0rmer/EWsMX/

Related

how to find duplicate dropdown row in a table using jquery?

There is a table which contains an user dropdown per row. Needs to prevent of selecting duplicate users of dropdown in the table.
While selecting the duplicate user in the above table as "easy",The js code should keep the first of user dropdowm the rest of duplicate user dropdown wants to remove from table.
HTML
Javascript Code
function checkDuplicateUserId(obj){
var user_id=$("#"+obj.id+" option:selected").val();
$('tbody#data tr select').each(function (i, row) {
if ($('tbody#data tr select').find('option[value="' + $(this).val() + '"]').size() > 1) {
alert();
}
});
}
function checkAlreadySelected(obj){
checkDuplicateUserId(obj);
var num = parseInt($(obj).attr('num'));
var user_id=$("#"+obj.id+" option:selected").val();
var next_user_id=$("#user_id_"+eval(num+1)+" option:selected").val();
if(user_id && typeof next_user_id == 'undefined'){
var row = updateSrNo(num);
$("#data").append(row);
}
}
As i mentioned in the js code, I have written a function as called as checkDuplicateUserId() to detect the duplicate dropdown from the table, Unfortunately the alert() not prompted while select the duplicate users.
What's the issue of jquery code which i have written wrongly there?
If you have other way to accomplish this, Please say it
Thanks in advance
Try this:
function checkDuplicateUserId(obj){
var user_id=$("#" +obj.id + " option:selected").val();
if( $('tbody#data tr select option:selected').filter( function(){ if( $(this).val() == user_id ) return true; } ).length > 1) {
alert('something');
}
}
You can do something like this:
function checkAlreadySelected(obj){
var user_id=$("#"+obj.id+" option:selected").val();
$('tbody#data tr select').each(function (i, row) {
if ($(this).val()==user_id) {
return false ;
}
});
return true ;
}

Need to append / delete id into hidden field on "change"

I ve got numérous checkboxes in my page, each time I click a checkbox, I get the id im interested in and I fill a hidden form. My script is working but if I unclick the checkbox, it should delete the id from the hidden field (right now it appends again the id in the hidden field). How can I writte such a script ? Here's my code so far:
$(document).ready(function() {
var string = "";
$('.checkbox').on('change', function() {
var subscription_id = $(this).parent().attr('id');
if(string == "") {
string = subscription_id;
} else {
string = string + ", " + subscription_id;
}
$('#select_players').val(string);
$('#subscription_ids_export').val(string);
})
})
You can simplify this by retrieving only the subscription_id values from checkboxes which are checked instead of adding/removing values each time.
Try this:
$('.checkbox').on('change', function() {
var subscriptionIds = $('.checkbox:checked').map(function() {
return $(this).parent().prop('id');
}).get().join(',');
$('#select_players').val(subscriptionIds);
$('#subscription_ids_export').val(subscriptionIds);
})
Example fiddle

How to validate specific input fields in a specific div

I am able to validate all fields within a div but I only want to validate specific fields. Here is a jsfiddle to show what I mean Once validation is passed the div is hidden. I have to enter data in all of the fields so if you check 'Yes' from the checkbox you will see a input field appear I don't want to include that and also if you select 'NoGame' from the dropdownlist once you enter data in all the fields apart from the two fields in the lower div (green border) and click the Test1 button you will see what I mean. Any suggestions?
This is the code which validates all fields and then Hides the div, which can also be seen in the fiddle
function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
$.each($div.find("input[type='text']"), function (i, input) {
if ($(input).val().length == 0 || $.trim($(input).val()) == '') {
result = false;
return;
}
});
return result;
}
$(document).ready(function(){
$("#hide").click(function(){
if (IsValid('contentone')) {
$('#contentone').hide();
};
});
});
Input fields of type text that you don't want to validate exclude them from the validation process
function IsValid(divid) {
var $div = $('#' + divid);
var result = true;
var excludeElement = ["reason"]; //<-- EXCLUDED ELEMENTS IDS
$.each($div.find("input[type='text']"), function (i, input) {
if ($.inArray($(input).attr('id'), excludeElement) < 0 && ($(input).val().length == 0 || $.trim($(input).val()) == '')) {
result = false;
return;
}
});
return result;
}

How to check if the any of my textbox is empty or not in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if inputs are empty using jQuery
I have form and textboxes, how will I determine if any of these textboxes is empty using javascript if else statement once a form button is clicked.
function checking() {
var textBox = $('input:text').value;
if (textBox == "") {
$("#error").show('slow');
}
}
Thanks in advance!
By using jQuery selectors for selecting the elements, you have a jQuery object and you should use val() method for getting/setting value of input elements.
Also note that :text selector is deprecated and it would be better to trim the text for removing whitespace characters. you can use $.trim utility function.
function checking() {
var textBox = $.trim( $('input[type=text]').val() )
if (textBox == "") {
$("#error").show('slow');
}
}
If you want to use value property you should first convert the jQuery object to a raw DOM object. You can use [index] or get method.
var textBox = $('input[type=text]')[0].value;
If you have multiple inputs you should loop through them.
function checking() {
var empty = 0;
$('input[type=text]').each(function(){
if (this.value == "") {
empty++;
$("#error").show('slow');
}
})
alert(empty + ' empty input(s)')
}
You can not use value with jquery object use val() function, But this will check only the first textbox returned by the selector.
Live Demo
function checking() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
}
You can attach blur event and do this validation on losing focus from each textbox.
Live Demo
$('input:text').blur(function() {
var textBox = $('input:text').val();
if (textBox == "") {
$("#error").show('slow');
}
});
Validation on submit button click according to discussion with OP
​Live Demo
$('#btnSubmit').click(function() {
$("#error").hide();
$('input:text').each(function(){
if( $(this).val().length == 0)
$("#error").show('slow');
});
});
Try this code:
var textBox = $('input:text').val();
if (textBox==""){
$("#error").show('slow');
}

Detect HTML Option Value Using jQuery [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get the text of the selected option of a select using jquery?
I have the following script:
<select id = "people">
<option value = "0">Choose</option>
<option value = "1">John</option>
<option value = "2">David</option>
</select>
How Can I use jQuery to detect the value of the option that is currently selected?
i.e. (pseudo-ish code)
if(people.option.text == "Choose"){
//Alert - Please make a selection
}else{
//Valid - do something
}
EDIT: code not working
echo("<script>");
echo("$(document).ready(function(){");
echo("$(\"#go\").click(function(e){");
echo("var selText = $(\"#people option:selected\").text();");
echo("if(selText == \"Choose\"){");
echo("}else{");
echo("window.location.href = \"viewprofile.php\";");
echo("}");
echo("});");
echo("});");
echo("</script>");
It constantly triggers the else statement and navigates away...
EDIT: Got it working -> changed .text() and val()
From your example looks like you want to get the selected text, not value.
So have this:
var selText = $("#people option:selected").text();
if(selText == "Choose") {
//Alert - Please make a selection
} else {
//Valid - do something
}
To get selected value and check it, have such code:
var selValue = parseInt($("#people").val(), 10);
if (selValue == 0) {
//Alert - Please make a selection
} else {
//Valid - do something
}
if (jQuery('#people option:selected').val()=="Choose"){
}
else{
}
Check the value that is selected using val, then take the appropriate action. Shown below in a form submission handler to prevent form submission. You might also want to consider using the validate plugin for this particular case, making the field required, and having the default option have no value.
$(function() {
$('form').submit( function() {
var selectedPerson = $('#people').val();
if (!selectedPerson || selectedPerson == '0') {
alert('you must choose an option for people');
return false;
}
// continue form validation and submission
});
});
To get the value of the selected <option>, use:
$('select').val()
To get the HTML content of the selected <option>, use:
$'select :selected').html()
And to check if a certain <option> is selected, use:
if ($('option').is(':selected')) ...
How about this:
$("select option:selected").each(function () {
if($(this).text()=="Choose") ...
else ...
});
if ($('#people [value!=0]:selected').length > 0){
//selected
} else {
//not selected
}

Categories

Resources