jquery $.get help - javascript

I am building a dynamic form in that the user can keep adding entries until they satisfied, to do this, I use this javascript, to pull in some html,
$('#add_another').click(function(e){
$.get('/admin/add_grade_course', function(data) {
$('#added_by_ajax').append(data);
});
e.preventDefault();
});
The HTML that is returned is a follows,
<fieldset>
<select name="course_type">
<option value="Classroom based learning">Classroom Based Learning</option>
<option value="Apprenticeship based learning">Aprenticeship Based Learning</option>
<option value="On the Job Learning">On The Job Learning</option>
</select>
<label for="course_names">Course Name</label>
<input type="text" name="course_names" value="<?php set_value('course_names');?>"/>
<?php echo form_error('course_names'); ?>
<label for="course_links">Course Links</label>
<input type="text" name="course_links" value="<?php set_value('course_links');?>"/>
<?php echo form_error('course_links'); ?>
<label for="grade_desc">Description of Grades Needed</label>
<textarea name="grade_desc"><?php set_value('grade_desc')?></textarea>
Delete
</fieldset>
My question is that as you can see there is nothing unique about the entry form that is created on the fly, if the user has added a new entry field and then decides they dont need it, how would I go about removing the last added form elements?, I assume I need to somehow get the parent fieldset for the clicked .remove_fields link? How would I do that, without selecting all the fieldsets on the page?

Use the closest-method:
// Add a delegated click-handler for clicks on remove-links
$('body').delegate('a.remove_fields', 'click',
// In the event handler, remove the fieldset this link belongs to
function (e) {
// this refers to the link that was clicked.
// closest traverse the DOM upwards until it finds an ancestor
// matching the selector. (i.e. a fieldset).
// After we find this ancestor, we remove it from the DOM.
$(this).closest('fieldset').remove();
}
);

The following will bind to the click event using the live() function and remove the selected entry. The live function is handy because it means that any dynamically added markup that matches the selector will have the function bound as it is added. This means that each time the user clicks the add_another link, the newly returned fieldset has the function bound to the click event of its remove_fields link.
$(function(){ //shorthand for $(document).ready(function(){
$('.remove_fields').live('click', function() {
//$(this).parent() returns the current fieldset, remove() removes it.
$(this).parent().remove();
});
});

Something like this might work:
var form_counter = 0;
$('#add_another').click(function(e){
$.get('/admin/add_grade_course', function(data) {
$(data).attr('id', 'form_' + form_counter);
var form_count_ref = form_counter;
$('a:last', data).onclick(function(){
$('form_' + form_count_ref).remove();
});
form_counter++;
$('#added_by_ajax').append(data);
});
e.preventDefault();
});

Related

Get Option Value OnClick with No Class/ID

I'm building an ecommerce website with 100 items. Each item has an item option (i.e. Small, Medium, Large). Each option has a value with an integer that identifies the option.
When the user clicks "Add to Cart," I need express that value as a variable. The problem is all of these items have the same exact class/id so I can't write an onclick function for each one.
How can I use jQuery to get the selected option value onclick without a class/id to identify it?
Basic structure of the item form:
<form>
<label>First Item</label>
<select>
<option value="6432">Large</option>
<option value="5332">Small</option>
</select>
<input type="submit" value = "Add to Cart">
</form>
Here's a Fiddle that shows what I'm talking about: http://jsfiddle.net/cusygh4o/
Thanks :-)
Try this:
$('input[type="submit"]').on('click', function(e) {
e.preventDefault();
alert($(this).prev('select').val());
});
Updated JSFiddle: http://jsfiddle.net/cusygh4o/1/
Note: if there is anything you can do to narrow down that 'input[type="submit"]' selector, you should. For example, if you have a parent element with an id, you could do something like '#shopping-items input[type="submit"]'.
jsFiddle Demo
Just base it off where the click occurred.
$("input[type=submit]").click(function(){
alert($(this).parents("form").find("select").val());
});
Use this
jQuery(document).ready(function(){
var selectedValue;
$('input[type="submit"]').on('click', function() {
selectedValue=jQuery('form select').val();
alert(selectedValue);
})
})
Lots of different ways to go about it: http://jsfiddle.net/cusygh4o/2/
$('form').on('submit', function(e) {
alert($(this).find('select').val());
});
Try this
<script>
function getValue(e){
value = e.closest('form').find('select').find(":selected").text();
alert(value);
}
</script>
Then replace all your <input type="submit" value = "Add to Cart"> with <input onclick="getValue($(this))" type="submit" value = "Add to Cart">

Run a Specific Function Depending on Which Drop-Down was Chosen

I am using this code I found to try and make this drop down menu. http://www.javascriptkit.com/script/cut183.shtml
Ignore my variables and values, they are all place holders.
For example, when I hit submit it runs the "gen" function.
Is there anyway I can have my code run a different function based on which drop-down option was selected?
<html>
<body>
<form name="doublecombo" form action"index.php" method="POST">
<p><select name="example" size="1" onChange="redirect(this.options.selectedIndex)">
<option>Amazon</option>
<option>Apple</option>
<option>Logitech</option>
<option>Nike</option>
</select>
<select name="stage2" size="1">
<option value="http://javascriptkit.com">Kindle Fire</option>
<option value="http://www.news.com">Kindle DX</option>
<option value="http://www.wired.com">Kindle Charger</option>
<option value="http://www.microsoft.com">Kindle Paperweight</option>
</select>
<input type="button" name="test" value="Generate"
onClick="gen()">
</p>
<script>
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("Kindle Fire","http://javascriptkit.com")
group[0][1]=new Option("Kindle DX","http://www.news.com")
group[0][2]=new Option("Kindle Charger","http://www.wired.com")
group[0][2]=new Option("Kindle Paperweight","http://www.microsoft.com")
group[1][0]=new Option("MacBook","http://www.cnn.com")
group[1][1]=new Option("iPhone","http://www.abcnews.com")
group[1][2]=new Option("iPad","http://www.yahoo.com")
group[1][3]=new Option("iMac","http://www.apple.com")
group[2][0]=new Option("G602 Wireless Gaming Mouse","http://www.hotbot.com")
group[2][1]=new Option("G19s Gaming Keyboard","http://www.infoseek.com")
group[2][2]=new Option("G430 Surround Sound Gaming Headset","http://www.excite.com")
group[2][3]=new Option("PowerShell Controller","http://www.lycos.com")
group[3][0]=new Option("Nike FuelBand","http://www.nike.com")
var temp=document.doublecombo.stage2
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function gen(){
location=temp.options[temp.selectedIndex].value
}
function exampleFunction(){
}
function anotherExampleFunction(){
}
</script>
</form>
</html>
</body>
Using Jquery's event handlers:
$(selector).on('click', gen);
$(selector).on('change', redirect);
These also have the following short-hands:
$(selector).click(gen);
$(selector).change(redirect);
Where selector is the element you want to attach the listeners too, by id or class or element name or other types of selectors.
In the case of select you can only use the change event. Look at the examples here.
Here is an example of what you are looking for: demo
var functions = {
func1: function(){console.log("func1 called")},
func2: function(){console.log("func2 called")},
func3: function(){console.log("func3 called")},
}
$( "select" )
.change(function () {
var selected = $( "select option:selected" );
functions[selected.val()]();
})
.change();
I select the select element, and attach a change event handler to it. When it changes, the handler functions selects the selected option (select option:selected means the selected option which is a child of select), then I simply call the functions from the functions object according to the options's value.

How to insert select data into input when do not have ID or class

How to insert select data into input when do not have ID or class.
HTML code:
<input type="text" name="employed_since" data-validators="required validate-date2"/>
<select id="field3" size="0" style="display: inline-block;">
<option value="" class="">.................
<select id="field4" size="0" style="display: inline-block;">
<option value="" class="">J
This is example js code when i have ID:
$('field3').addEvent('change', function() {
if (this.selectedIndex != 0 && $("field4").selectedIndex != 0) {
$("employed_since").value = this.value + $("field4").options[$("field4").selectedIndex].value;
$("employed_since").fireEvent('change');
}
});
$('field4').addEvent('change', function() {
if (this.selectedIndex != 0 && $("field3").selectedIndex != 0) {
$("employed_since").value = $("field3").options[$("field3").selectedIndex].value + this.value;
$("employed_since").fireEvent('change');
}
});
You could attach the change event to the form since that event bubbles. In your event handler, the this variable references the form. The handler also receives a single argument called event. The event.target property is the form field that just changed.
To access form fields without the Id property, simply use this.fields.field_name where your replace "field_name" with the value of a form field's name attribute.
You can use any css selector to grab an element using jQuery. For example
$('input[name=employed_since]').val = '1984';
Will set the value of the input element with the name employed_since.
See this reference to all the available css selectors. I usually like to open up the javascript console on the page I'm working with and just trying out the selection until I get it just right.
The command using the native querySelector function would be very similar.
document.querySelector('input[name=employed_since]').value = '1984';

Only first input field automatically being filled in by JQuery function

I'm trying get a form to fill in inputs automatically when a user puts in information in the footage field which should then be plugged into an equation with JQuery and then the answer should be output in postQuantity. Since the user can add inputs the form is set up that each footage should go with a corresponding postQuantity signified by its suffix number. So that footage2 should be used to find postQuantity2 and 3 for 3 and so on. The problem is that only the first field is automatically filling in and that anytime a different footage class is changed nothing happens. Any insight on where I went wrong and advice on how to fix it will be greatly appreciated! Thanks! Here is a JSFiddle - http://jsfiddle.net/gv0029/TwH5n/
HTML:
<form>
<fieldset id="fence">
<div class="inputFence">
<fieldset class="fenceDescripton">
<legend><strong>Fence Description</strong></legend>
<label>Footage<input name="footage_1" class="footage" /></label>
<select name="fenceHeight_1" class="fenceHeight">
<!--got rid of "select" from the value. not needed at all-->
<option value="">Select Fence Height</option>
<!--got rid of the ids completely. the numbers from the values are all you need-->
<option value="6">6 Ft.</option>
<option value="8">8 Ft.</option>
</select>
</fieldset>
<fieldset class="post">
<legend><strong>Post Type</strong>
</legend>
<label>Post Quantity:
<input type="postQuantity" name="postQuantity_1" class="postQuantity" value="" />
</label>
<select name="postMeasurements_1" class="postMeasurements">
<option value="">Select Post Measurements</option>
<option value="23/8 x .065 x 8">2 3/8 x .065 x 8</option>
<option value="23/8 x .095 x 8">23/8 x .095 x 8</option>
</select>
</fieldset>
</div>
</fieldset>
<div>
<input type="button" id="btnAddFence" value="Add Another Fence" />
<input type="button" id="btnDelFence" value="Remove Fence" />
</div>
</form>
JS:
//Quantity for Posts
$("[class^='footage']").bind('keypress keydown keyup change', function(){
var footage = parseFloat($(this).val(),10);
var total = '';
var parts = $(this).attr('name').split("_");
var fenceNumber = parts[1];
if(!isNaN(footage)){
total = Math.ceil(footage /7);
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val(total.toString());
} else {
$(":input[name='postQuantity_" + fenceNumber + "'" + ']').val("");
}
});
//Dynamic Fence Input Fields
$('#btnAddFence').click(function () {
// create the new element via clone()
var newElem = $('.inputFence:last').clone();
// insert the new element after the last "duplicable" input field
$('.inputFence:last').after(newElem);
// enable the "remove" button
$('#btnDelFence').removeAttr('disabled');
//get the input name and split into array (assuming your clone is always last)
var parts = $('.fenceHeight:last').attr('name').split("_");
//change the second element of the array to be one higher
parts[1]++;
//join back into a string and apply to the new element
$('.fenceHeight:last').attr('name', parts.join("_"));
//do the same for other two inputs
parts = $('.postQuantity:last').attr('name').split("_");
parts[1]++;
$('.postQuantity:last').attr('name', parts.join("_"));
parts = $('.postMeasurements:last').attr('name').split("_");
parts[1]++;
$('.postMeasurements:last').attr('name', parts.join("_"));
parts = $('.footage:last').attr('name').split("_");
parts[1]++;
$('.footage:last').attr('name', parts.join("_"));
// business rule: you can only add 5 names
//if (newNum == 5)
//$('#btnAdd').attr('disabled','disabled');
});
$('#btnDelFence').click(function () {
//remove the last inputFence
$('.inputFence:last').remove();
// if only one element remains, disable the "remove" button
if ($('.inputFence').length == 1) $('#btnDelFence').attr('disabled', 'disabled');
});
$('#btnDelFence').attr('disabled', 'disabled');
I think you want somethign like this:
http://jsfiddle.net/TwH5n/3/
the line I changed was:
$(document.body).on('keydown', '[class^="footage"]'
this binds the event to all future '[class^="footage"]' elements
ideally you would not do this on body since its not efficient. find a closer parent, or attach the event to each clone upon creation.
The jsfiddle is wrong
Anyway, you are using .bind method which is bind event handlers to currently existing elements. You can use .live method which is working for selector instead of elements, but this is deprecated in version 1.7, and removed in 1.9
As of http://api.jquery.com/bind/
For more flexible event binding, see the discussion of event
delegation in .on() or .delegate().
Hope this helps
P.S. Right example without using deprecated methods
$('form').on('keypress keydown keyup change',"[class^='footage']", function(){});
http://jsfiddle.net/TwH5n/7/

Append to a div with a recurring class

I have a piece of JS that appends the following to a web form on the click of a button. When the div .remove is clicked the closest new-attribute div is removed. It works fine.
<div class="new-attribute">
<h3>New Attribute</h3>
<label for="attributeName3">Name:</label>
<input class"attribute"="" type="text" name="attributeName3">
<label for="attributeType3">Type:</label>
<select id="t" class="attribute" name="attributeType3">
<option value="text" selected="">Text</option>
<option value="checkbox">Checkbox</option>
<option value="select-list">Select Option List</option>
<option value="notes">Notes</option>
</select>
<div class="option"></div>
<div class="remove">Delete</div>
</div>
In the div "option" I have code to add another form field on the selection of "select-list" in the select input. It does not work. I do not know why. No variable names are clashing. I'm away I shouldnt give the select an id because it is recurrent, I just want to get it working before I make it compliant.
Heres the Js that I'm having trouble with:
//select temp
var select="<div class=\"new-option\">"
+ "<h3>new option</h3>"
+ "<label for=\"attributeName"+count+"\">New otion:</label>"
+ "<input class\"attribute\" type=\"text\" name=\"attributeName"+count+"\">"
+ "</div>";
//get value of select
$('#t').change(function() {
var selectVal = $('#t :selected').val();
if (selectVal == "select-list") {
$(this).closest('.option').append(select);
}
});
The code works with $(select).appendTo('.option');
However it appends the code to every instance of the "option" class on the page. I only want it to append to the current or closest one.
Thank you in advance
The problem is because closest() looks up the DOM for the nearest parent element matching the selector, but .option is a sibling of #t. Try using next() instead:
$('#t').change(function() {
if ($(this).val() == "select-list") {
$(this).next('.option').append(select);
}
});
Try this
http://jsfiddle.net/7WC4G/1/
$('#bob').change(function(){
$('#nuform').append('<p>your new form here</p>');
});
Avoid using next, prev as it could fail if you change the order.
Instead try using siblings instead of closest in your code:
$(this).siblings('.option').append(select);
Read more about it here: http://api.jquery.com/siblings/

Categories

Resources