Skip to content

Instantly share code, notes, and snippets.

@seanrclayton
Created March 26, 2014 18:00
Show Gist options
  • Save seanrclayton/9789435 to your computer and use it in GitHub Desktop.
Save seanrclayton/9789435 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#target").blur(function(){
var name = $("#target").val();
for (var i = 1; i < name; i++) {
$("#myspan").clone().appendTo("#myspan")
}
});
$("#target").click(function(){
("#myspan").remove();
});
$('#myform :checkbox').click(function() {
var $this = $(this);
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
$("#myspan").hide()
} else {
$("#myspan").show()
}
});
});
</script>
</head>
<body>
<input id="target" type="text">
<p>How many people will be joining you?</p>
<form id="myform">
<input type="checkbox" name="check1" value="check1">Im flying stag
<br><br>
<%= text_field_tag :name %> first name <br>
<span id="myspan"><%= text_field_tag :name %> guests name<br></span>
</body>
</html>
@DrewML
Copy link

DrewML commented Mar 26, 2014

Couple suggestions not related to functionality:

 $("#target").blur(function(){
              var name = $("#target").val();

To prevent doing another lookup against the DOM, change the second reference to #target to be $(this).val(), since jQuery sets the "this" value for you.

$("#myspan").clone().appendTo("#myspan")

This forces 2 lookups of the same element in the DOM. Cache the results of the lookup instead, like this:

var $myspan = $('#myspan')
$myspan.clone().appendTo($myspan);

Couple places where you could improve performance by caching your calls to the $() constructor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment