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

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

Related

While loop to hide div elements

I am trying to create searchable content with the help of some JS yet am having trouble hiding the content when there is no input in the search field.
Here is my script:
var $searchContainer = $("#search");
var $contentBoxes = $searchContainer.find(".content");
var $searchInput = $searchContainer.find("#search-input");
var $searchBtn = $searchContainer.find("#search-btn");
$searchBtn.on("click", searchContent);
$searchInput.on("input", searchContent);
while($searchInput == null) {
for($contentBoxes) {
hide();
}
}
function searchContent(){
var userInput;
//Check if call comes from button or input change
if($(this).is(":button")){
userInput = $(this).siblings("input").val();
} else {
userInput = $(this).val();
}
//make the input all lower case to make it compatible for searching
userInput = userInput.toLowerCase();
//Loop through all the content to find matches to the user input
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
};
I understand a while loop could have a condition where if userInput is equal to null it would loop through each content box and hide the element.
Something like this maybe?
while($searchInput == null) {
$contentBoxes.each(function(){
hide();
}
}
Any help would be greatly appreciated.
You would need to update your userInput variable every cycle of the loop because the userInput value never gets updated. Nonetheless this not a good way to do this because you will block your entire application.
There is no need for a loop, just use an if statement. Also, because this function gets executed when the value of the input is changed, there is no need to use this.
You could put this block of code beneath your $contentBoxes.each function:
$contentBoxes.each(function(){
var headerText = $(this).find(".title").text();
var contentText = $(this).find(".description").text();
//add the title and content of the contentbox to the searchable content, and make it lower case
var searchableContent = headerText + " " + contentText;
searchableContent = searchableContent.toLowerCase();
//hide content that doesn't match the user input
if(!searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}
});
if (userInput === null) {
$contentBoxes.each(function(){
$(this).hide();
});
}
I think it will be work like this. You just check if search input !== null and dont hide any content in this case
if($searchInput != null && !searchableContent.includes(userInput)){
$(this).hide();
} else {
$(this).show();
}

Having Button not run Function With Empty Input Field

So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code

how to get value from textbox on click of button in jquery

enter image description here
this is the image, in this, i have a button when I click the button it should show me the updated value of textbox into the alert box. I have coded something like this.
$(document).on('click', '#Button1', function () {
var newStr = document.getElementsByName('input');
var str = '';
for (var i = 0; i < newStr.length; i++)
{
str = str + newStr.item(i).value;
}
alert(str);
});
But things are not working properly. Need help thanxx.
$(document).on('click', '#table1 tr', function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
$(tableData).each(function (index, value) {
$('#txt' + index).val(value);
});
});
this is sending table data to the textbox. I just want to get all the value of textbox into one variable and want to check that value for further process.
you haven't gave your html. but using this you can access all your input type.
$("#formID :input").each(function(){
var input = $(this);
});
or IF u want to access only input type = text
use
$("#formID input[type=text]")
Hope this will help you out

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 append and remove checkbox values to and from hidden field

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/

Categories

Resources