jquery show/hide div on change of value in form input

Hi,

I have an input which can be populated by clicking a list item or by typing into the input box.  the string created in the input box is a selection of usernames seperated by a comma.

I would like to create a jquery function that hides / shows a div which contains a second for input box. I would like it if the jquery hides the div if there is no comma (only one username). If there are two usernames or more (one or more commas) then show the input box

here is what i have so far

//HIDE/SHOW SUBJECT
		$('#msg_to').change(function(){
			var string=$(this).val().replace(" ", "");	
			//COUNT CHARACTERS
			var counter=string.split(",");
			alert(string);
			if(counter.length >= 1){
				//CHANGE DIV CLASS
				$('#subject_show').show("fast");
				alert(counter);	
			}else{
                                $('#subject_show').hide();

                       }
		})

Open in new window


this is the form
<form class="form-horizontal" method="post" enctype="multipart/form-data" parsley-validate="" name="new_msg" id="new_msg" action="ajax/messages_main.php?new">
                          <div class="form-group">
                            <label for="msg_to" class="col-sm-2 control-label">To: </label>
                            <div class="col-sm-8">
                              <input type="text" class="form-control ui-autocomplete-input parsley-validated" id="msg_to" name="msg_to" parsley-trigger="change" parsley-required="true" autocomplete="off">
                            </div>
                          </div>
                     
                          <div class="form-group" id="subject_show">
                            <label for="msg_subject" class="col-sm-2 control-label">Subject :</label>
                            <div class="col-sm-8">
                              <input type="text" class="form-control" id="msg_subject" name="msg_subject">
                            </div>
                          </div>
                     
                          <div class="form-group">
                            <label for="msg_msg" class="col-sm-2 control-label">Message: </label>
                            <div class="col-sm-8">
                              <textarea type="text" class="form-control parsley-validated" id="msg_msg" name="msg_msg" placeholder="Start typing your message..." rows="10" parsley-trigger="keyup" parsley-required="true"></textarea>
                            </div>
                          </div>
                          <div class="form-group">
                          	<div class="col-sm-10">
                          		<input type="submit" class="btn btn-green pull-right" name="msg_send" id="msg_send" value="Send">
                            </div>
                          </div>
                      </form>

Open in new window


thanks in advance
LVL 6
J NUnicorn wranglerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Randy PooleCommented:
what problem are you running into? the only thing I can see is
if(counter.length >= 1)

Open in new window

should be
if(counter.length > 1)

Open in new window

0
GaryCommented:
You want to hide/show the Subject div?

Simply this with the subject div initially hidden

http://jsfiddle.net/LYj5f/2/

$("#msg_to").keyup(function(){
    $(this).val().indexOf(",") >= 0?$("#subject_show").show():$("#subject_show").hide()
})

Open in new window

0
J NUnicorn wranglerAuthor Commented:
@randy  

thanks but i want it to be greater or equal to 1(is that not possible?)

@gary
.keyup -> as i mentioned a user can input values into the form by click list items. so i wanted a function that could do
    1) keyup( or similar) if the user decides to type in the values
    2) onchange (not sure if this is correct) if the users is changing (ie including/exluding values) by selecting items on a list
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

GaryCommented:
Then change it to

$(document).on("keyup,change","#msg_to",function(){
    $(this).val().indexOf(",") > 0?$("#subject_show").show():$("#subject_show").hide()
})

Open in new window

0
GaryCommented:
Should be a space not a comma in the event

http://jsfiddle.net/LYj5f/3/
$(document).on("keyup change","#msg_to",function(){
    $(this).val().indexOf(",") > 0?$("#subject_show").show():$("#subject_show").hide()
})

Open in new window

0
J NUnicorn wranglerAuthor Commented:
Hi,

i tried this code and it did not work and i checked the console for any errors and there was none
$(document).on("keyup change","#msg_to",function(){
    $(this).val().indexOf(",") > 0?$("#subject_show").show():$("#subject_show").hide()
})

Open in new window


additionally, i would like to keep the if and else statments becuase i would like to add some more changes to attr
0
GaryCommented:
What doesn't work?

http://jsfiddle.net/LYj5f/4/
0
J NUnicorn wranglerAuthor Commented:
Hi,

it looks like i have additional JS that is restricting this function

here is all of my JS
	/*AUTO COMPLETE FORM FUNCTION */
		$(function() {
			var availableUsers = [
			  "Daisy Duke","Gorilla","Thechef","Niggazbcrayfish","Blackout Menace","Samscratch","Schacattack77","Jooombee","Expert-test","Mikemike",			];
		  function split( val ) {
			return val.split( /,\s*/ );
		  }
		  function extractLast( term ) {
			return split( term ).pop();
		  }
	   
		  $( "#msg_to" )
			// don't navigate away from the field on tab when selecting an item
			.bind( "keydown", function( event ) {
			  if ( event.keyCode === $.ui.keyCode.TAB &&
				  $( this ).data( "ui-autocomplete" ).menu.active ) {
				event.preventDefault();
			  }
			})
			.autocomplete({
			  minLength: 0,
			  source: function( request, response ) {
				// delegate back to autocomplete, but extract the last term
				response( $.ui.autocomplete.filter(
				  availableUsers, extractLast( request.term ) ) );
			  },
			  focus: function() {
				// prevent value inserted on focus
				return false;
			  },
			  select: function( event, ui ) {
				var terms = split( this.value );
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push( "" );
				this.value = terms.join( ", " );
				return false;
			  }
			});
		});
		
		/*TOGGLE CLASS*/
		var names = {};
		$("#chat-inbox li a").on("click", function(){
			if($(this).hasClass("active")){
				 // remove from form
				$(this).removeClass("active").addClass("unread");
				var name = $.trim($(this).find(".media-heading").text());
				delete names[name];
				$("#msg_to").val(Object.keys(names));
			}else{
				// add to form
				var name = $.trim($(this).find(".media-heading").text());
				names[name] = name;
				$("#msg_to").val(Object.keys(names));
				$(this).removeClass("unread").addClass("active");
			}
			
		});
		
		//HIDE/SHOW SUBJECT
		$("#msg_to").on("keyup change", function(){
			if($(this).val().indexOf(",") > 0){
				$("#subject_show").attr("style", {display: "block"});
				
			}else{
				$("#subject_show").attr("style", {display: "none"});
				
			}
			
		});

Open in new window

0
J NUnicorn wranglerAuthor Commented:
ignore my last comment
0
J NUnicorn wranglerAuthor Commented:
Hi,

i changed the code so i could include more functions which i initially intended however there is a problem

using the below code, i can select items on a list and then input values based on the list item i have selected. When i select one user. the code @gary supplied works and does not execute. If i select another user which results in the input box being populated with user1, user2, the js does not work.
/*TOGGLE CLASS*/
		var names = {};
		$("#chat-inbox li a").on("click", function(){
			if($(this).hasClass("active")){
				 // remove from form
				$(this).removeClass("active").addClass("unread");
				var name = $.trim($(this).find(".media-heading").text());
				delete names[name];
				$("#msg_to").val(Object.keys(names));
			}else{
				// add to form
				var name = $.trim($(this).find(".media-heading").text());
				names[name] = name;
				$("#msg_to").val(Object.keys(names));
				$(this).removeClass("unread").addClass("active");
			}
			
		});

Open in new window


if i type the input values into the input box as (user1, user2) the below code works fine
//HIDE/SHOW SUBJECT
		$("#msg_to").on("keyup change", function(){
			if($(this).val().indexOf(",") > 0){
				$("#subject_show").attr("style", "display: block");
				$("#msg_subject").attr("parsley-required", "true");
				
			}else{
				$("#subject_show").attr("style", "display: none");
				$("#msg_subject").attr("parsley-required","false");
				
			}
			
		});

Open in new window


so my click event is not registering which i though would be caught with the change event listener
0
GaryCommented:
Can you post your real HTML/JS as you have it now instead of me guessing what is on the page.
0
J NUnicorn wranglerAuthor Commented:
might be easier if i just post the link


http://www.bushbrigade.com/bushbase/system/messages.php?new#


user: expert-exchange
pass: 3XP3rt!!!!
0
GaryCommented:
Is this still outstanding, seem to have missed your reply.
0
J NUnicorn wranglerAuthor Commented:
Hi,

Yes i have not gotten this to work yet.

The function works if the user is typing in user input. However, i also have a function that updates the field value by clicking list items. if the user selects the input values the above function does not work.. i can paste the entire page but i though it would be easier for you to just look at my page instead so i posted the link

http://www.bushbrigade.com/bushbase/system/messages.php?new


user: expert-exchange
pass: 3XP3rt!!!!
0
GaryCommented:
I know why I didn't come back to this - cannot login
0
J NUnicorn wranglerAuthor Commented:
Hi,

i just tried the user pass and it worked for me
0
GaryCommented:
After

$("#chat-inbox li a").on("click", function(){

add

$("#msg_to").trigger("change")
0
GaryCommented:
Tell a lie, add it where I have bolded it

            $("#chat-inbox li a").on("click", function(){
                  if($(this).hasClass("active")){
                         // remove from form
                        $(this).removeClass("active").addClass("unread");
                        var name = $.trim($(this).find(".media-heading").text());
                        delete names[name];
                        $("#msg_to").val(Object.keys(names));
                  }else{
                        // add to form
                        var name = $.trim($(this).find(".media-heading").text());
                        names[name] = name;
                        $("#msg_to").val(Object.keys(names));
                        $(this).removeClass("unread").addClass("active");
$("#msg_to").trigger("change")
                  }
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
J NUnicorn wranglerAuthor Commented:
thanks a lot !!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.