jQuery - append string to input when changed - javascript

I have multiple select inputs on a page and I'd like to set all of them to have a particular option selected if a checkbox is checked
Once the form is submitted the inputs that have been updated will be looped through and sent to the database, so I have a function to append a string to the option value which is called on change of the select
This is all working great, however I'd like to append the updated string (to the value, not text) when the select option is changed by the checkbox being checked, but can't seem to get this to work
Fiddle https://jsfiddle.net/69zzr6xa/2/
I've tried looping through each select like so and then checking if the second option is already selected. If not, append the string, but it doesn't appear to work
$('select').each(function() {
if (!$(this).$('option').text == 'Two') {
var inputname = $(this).find(":selected")[0].value;
$(this).(":selected").val(inputname + "-updated");
}
});

I think this is what you are looking for.
function set_to_two() {
$('option:nth-child(2)').each(function(){
$(this).prop('selected', true);
if( $(this).val().indexOf('-updated') < 0 ){
$(this).val( $(this).val() + "-updated" );
}
});
set_updated();
}

Related

javascript add value to id based on select option value conditional

First off, I know I should know this. I am just not connecting the dots.
I have jquery working with a select menu so that when an option is selected, it's value is added to a hidden id in my form.
What I need, is that when an option is selected in this same select menu, depending on which option is selected, an email becomes the value in a different hidden id in the form.
I have an if conditional in my jsfiddle but it is not working. Any help is appreciated. Thanks! Peter T
jQuery(document).ready(function() {
// pass the title of the selected topic option to a hidden 'topic' form field
jQuery('select#recipient_email').change(function() {
var topic = jQuery('select#recipient_email option:selected').attr('title')
// set the hidden input's value
jQuery('#college2').val(topic);
//var topic_var = jQuery('#college2').val(topic);
if ((jQuery('#college2').val(topic)) == "Var 1")
{
$("#recipient_email_user").val("John.Doe#mail.com");
}
if ((jQuery('#college2').val(topic)) == "Var 2")
{
$("#recipient_email_user").val("Jane.Doe#mail.com");
}
})
})
jsfiddle
This line is wrong
if ((jQuery('#college2').val(topic)) == "Var 1")
You are setting the value and it returns the jQuery object, it is the equivilant of jQuery('#college2') == "Var 1"
If should just be
if (topic == "Var 1")

Clear a form and populate jquery

I am trying to clear a form and then repopulate it with new data. I have a page that has a list of search histories, along with a "search again" button, when clicked, it takes that search history string, split it, then match those again all the various form items; checkbox, radio, etc. The form has basically every kind of form element in it and everything is populating like I want it to except the checkboxes. The first time I click the populate form button, it works fine, but after the first click all the checkboxes start going haywire...some items populating like they should, some not, in a strange random pattern. I have not included the html because I don't think it is necessary but if anyone needs more info, please let me know.
This resets the form. I have tested this independently and it works.
function form_reset(){
$('#hosp_search_form')[0].reset();
$('#hosp_search_form').find("input[type=text], textarea").val("");
$('input[type=checkbox]').each(function(){
$('input[type=checkbox]').removeAttr('checked');
});
$('input[type=number]').val('');
$('input[type=radio]').each(function(){
$(this).removeAttr('checked');
});
On click, first clear the form of previous values, then grab the other needed values and format them...this part gets a little ugly in sections but I have consoled out all the values and everything is how it should be.
$('.search_again_btn').on('click', function(){
form_reset();
$('#hosp_search_form').find('input[type=checkbox]').removeAttr('checked');
var id = $(this).data('id');
var searchstring = $('#searchstring_' + id).text();
var patientcode = $('#patientcode_' + id).text();
var mrn = $('#mrn_' + id).text();
var first_name = patientcode.substr(0,2);
var last_name = patientcode.substr(2,2);
var age = patientcode.substr(4,3);
var gender = patientcode.substr(6,2);
var age = age.replace(/\D+/g, '');
gender = gender.replace(/[0-9]/g, '');
Populates some of the form, works fine
//populate fields in search form
$('input[name=fn]').val(first_name);
$('input[name=ln]').val(last_name);
$('input[name=patientage]').val(age);
$('input[name=mrn]').val(mrn);
Populate another part of the form, also always works as needed
//populate gender fields
if(gender == 'F'){
$('.female').attr('checked', 'checked');
}
if(gender == 'M'){
$('.male').attr('checked', 'checked');
}
Here is where I suspect the issue is. splitsearch is a long string (a previous search history) with items separated by a . and they get split into separate items. I console logged this, it correctly breaking it into the smaller values like I need, then iterate through those and iterate through all the checkboxes which each have a data attr holding values that can be in the splitsearch. If a value matches, it should make it checked. This works every time the first time, for any combo of splitsearch/search string values, but after the first time, I don't know what it is doing. I expect that each click, the form is cleared and it does the value matching again as I described.
//populate checkboxes
var splitsearch = searchstring.split('. ');
$.each(splitsearch, function(key, value){
$('input[type=checkbox').each(function(keyb, checkbox){
item = $(checkbox).data('services');
if(item == value){
$(this).attr('checked', 'checked');
console.log($(this));
}
});
This is doing the same as the above but works every time...probably because there is never multiple combinations like with checkboxes.
$('input[name=payor]').each(function(k, radio){
if(value == $(radio).data('payors')){
$(this).attr('checked', 'checked');
//console.log($(this));
}
});
Also like the above and works.
$('input[name=bedtype]').each(function(keyc, radio){
bed = $(radio).data('bed');
if(bed == value){
$(this).attr('checked', 'checked');
}
});
This part below is quite ugly but is populating the form like I need every time.
//if searchstring contains Needs Transportation, returns true, else returns false
if(value.indexOf("Needs Transportation") > -1 === true){
$('.transyes').attr('checked', 'checked');
}
if(value.indexOf("Near hospital") > -1 != true){
$('input[name=desiredzip]').val(searchstring.substr(5,5));
}
if(value.indexOf("5 mile radius") > -1 === true){
$('.miles_5').attr('checked', 'checked');
}
if(value.indexOf("10 mile radius") > -1 === true){
$('.miles_10').attr('checked', 'checked');
}
if(value.indexOf("15 mile radius") > -1 === true){
$('.miles_15').attr('checked', 'checked');
}
if(value.indexOf("20 mile radius") > -1 === true){
$('.miles_20').attr('checked', 'checked');
}
});
Scrolls the window up to the populated search form and show it.
window.scrollTo(0,100);
$('#search_show').show();
});
Just a thought but, it might help you to restructure your code a bit to keep it DRY.
// used to Hold search data in local or global
var data;
function form_reset() {
// clear form
}
function get_search_data() {
// populate data with search results
}
function form_populate() {
// use data to populate form
}
$('.search_again_btn').on('click', function(){
get_search_data();
form_reset();
form_populate();
});
// Initial Load of form
get_search_data();
form_populate();
that way you use the same population function initially as you do when you refresh and it forces you to put your data into a variable that can be seen in both the clear and populate functions removing your reliance on this and $(this).
also you need to bear in mind that the value of this inside a click function is going to be in the context of the click event itself and not the JavaScript object that the rest of your code belongs to.

How can I get the value of selected optgroup with jquery and select2?

I use select2 for selectbox and made <optgroup> selectable, but I can't get the value when I select it.
It's very important to get all options of the <optgroup> when you type optgroup name, as a result I can't replace <optgroup> with ususal <option>.
See jsfiddle example http://jsfiddle.net/iptspl/41r158dm/1/
You can try using the choice value on the event (if it exists) then check that for children and then combine their values.
on("select2-selecting", function(e) {
var value, choice = e.choice;
if(choice.children && choice.children.length > 0) {
value = [];
$(choice.children).each(function(index, child) {
value.push($(child.element).val());
});
value = value.join(",");
} else {
value = e.val;
}
alert(value);
});
At any rate, whatever you do you will most likely need to do something similar which is detect if it is an optgroup and then traverse the children and create the value.

.val with invalid value on select

I have a <select>, and on button click users can select the next option:
$(".someButton").on('click', function () {
var $opt = $("select :selected");
$("select").val($opt.next().val());
});
The problem is that on the last option, $opt.next().val() returns some unselectable value, and apparently jQuery selects the first option by default. What I would like is for it to stay on the last option.
Is there any way to do this (preferably without checking the position of $opt or the length of $opt.next())?
Here's a more efficient way to do it:
$(".someButton").on('click', function () {
var el = $("select")[0];
el.selectedIndex = Math.min(el.selectedIndex + 1, el.length - 1);
});
If you want to stick to jQuery, set the option to selected:
$opt.next().prop('selected', true);
If $opt is the last one, .next() will return an empty set, so nothing will change.
I would just handle the case to be honest. It would be simple to add the following:
if(!$opt.is(':last-child')) {
$("select").val($opt.next().val());
}

add and remove a certain value from a text field

each checkbox that i check, i fill the input with it's id
now, how can i retrieve this id that i put inside the input if the user uncheck the checkbox?
exp:
estate SC,SP was checked;
input recieve SC,SP value in this format = SC,SP
but the user uncheck the checkbox with SC value, then SC should be removed from the input.
this is what i'm doing to fill the input with the checkboxes.
var separador = ",";
var estadosS = "";
$(".checkboxEstados").live("click", function(){
if($(this).is(":checked")){
estadosS += (estadosS == "") ? "" : separador;
estadosS += $(this).attr("id");
$("#holdEstados").val(estadosS);
}else{
// now i'm just cleaning all the input,
// but i need to clean only the checkbox that was unchecked
$("#holdEstados").val("");
}
});
dont know if i was clear, any question, be my guest.
Thanks.
An easy way to solve this is to avoid parsing and removing parts of the data. Instead of trying to remove 'SC', instead regenerate the entire contents of the text field each time any checkbox is selected.
When a checkbox click event is detected, deleted the contents of the text input field, scan all of the selected checkboxes, and include their IDs in the text input field.
You're logic can be greatly simplified. Simply grab each checkbox that is checked when the click event fires:
$(".checkboxEstados").live("click", function() {
var aryIds = new Array();
$(".checkboxEstados:checked").each(function() {
aryIds.push($(this).attr("id"));
});
$("#holdEstados").val(aryIds.toString());
});
Here's a working fiddle.
I would store the value in an array and add and remove values from it and then write the array to the output instead of trying to parse the text each time:
var estadosS = [];
$(".checkboxEstados").live("click", function(){
var index;
if($(this).is(":checked")){
// append the id to the list
estadosS.push($(this).attr("id"));
}else{
index = estadosS.indexOf($(this).attr("id"));
if(index > -1) {
estadosS.splice(index, 1);
}
}
$("#holdEstados").val(estadosS.join(separador));
});
If all you are aiming to do is get a list of the checked values from all the check boxes, you could do:
$('.checkboxEstados:checked').each(function(){
alert($(this).val());
});
And that should return all the check box items that have been checked. Then you don't have to worry about adding and removing data from a text box. I'm just alerting the value, you would want to store them into an object or something more useful.

Categories