Solved

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

Posted on 2014-07-22
19
2,644 Views
Last Modified: 2014-08-05
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
0
Comment
Question by:M. Jayme Nagy
  • 9
  • 9
19 Comments
 
LVL 21

Expert Comment

by:Randy Poole
ID: 40212131
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
 
LVL 58

Expert Comment

by:Gary
ID: 40212132
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40212164
@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
 
LVL 58

Expert Comment

by:Gary
ID: 40212194
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
 
LVL 58

Expert Comment

by:Gary
ID: 40212303
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40213505
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
 
LVL 58

Expert Comment

by:Gary
ID: 40214331
What doesn't work?

http://jsfiddle.net/LYj5f/4/
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40215146
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40215165
ignore my last comment
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40215204
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
 
LVL 58

Expert Comment

by:Gary
ID: 40215731
Can you post your real HTML/JS as you have it now instead of me guessing what is on the page.
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40215752
might be easier if i just post the link


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


user: expert-exchange
pass: 3XP3rt!!!!
0
 
LVL 58

Expert Comment

by:Gary
ID: 40237419
Is this still outstanding, seem to have missed your reply.
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40241715
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
 
LVL 58

Expert Comment

by:Gary
ID: 40241775
I know why I didn't come back to this - cannot login
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40241780
Hi,

i just tried the user pass and it worked for me
0
 
LVL 58

Expert Comment

by:Gary
ID: 40241841
After

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

add

$("#msg_to").trigger("change")
0
 
LVL 58

Accepted Solution

by:
Gary earned 500 total points
ID: 40241855
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
 
LVL 6

Author Closing Comment

by:M. Jayme Nagy
ID: 40242044
thanks a lot !!!
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now