Link to home
Start Free TrialLog in
Avatar of J N
J N

asked on

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
Avatar of Randy Poole
Randy Poole
Flag of United States of America image

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

Avatar of Gary
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

Avatar of J N
J N

ASKER

@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
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

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

Avatar of J N

ASKER

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
Avatar of J N

ASKER

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

Avatar of J N

ASKER

ignore my last comment
Avatar of J N

ASKER

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
Can you post your real HTML/JS as you have it now instead of me guessing what is on the page.
Avatar of J N

ASKER

might be easier if i just post the link


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


user: expert-exchange
pass: 3XP3rt!!!!
Is this still outstanding, seem to have missed your reply.
Avatar of J N

ASKER

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!!!!
I know why I didn't come back to this - cannot login
Avatar of J N

ASKER

Hi,

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

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

add

$("#msg_to").trigger("change")
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of J N

ASKER

thanks a lot !!!