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">
Related
I'm trying to get values from select option box. but i get the first option box value only.
i want all option box values which is selected.suppose in code there is 10 select option box is created, when user clicks on button then i want all that 10 select option box values and get stored in a variables or display that options which is selected by the user.
i have done some code please refer my work from comment section it is on the jsfiddle website. for more better understanding you can refer that. sorry for my rookie language, i'm new to stackoverflow. please don't hesitate to edit my information i would like that.
Have a look on the following jsfiddle link:
[jsfiddle.net/ypb9zLe8/][1]
[1]: http://jsfiddle.net/ypb9zLe8/
Removed some code and inserted one extra button. Have a look.
The id for all the elements are same in your code. Use document.querySelectorAll
to get the list of elements.
function getdata() {
var num = document.getElementById("number").value;
console.log(num);
$(document).ready(function() {
for (var i = 0; i < num; i++) {
$('<div><select id="select-meal-type' + i + '"><option value="TYPE A">TYPE A</option><option value="TYPE B">TYPE B</option><option value="TYPE C">TYPE C</option></select><br></div>').appendTo('#container');
}
});
}
function getValues() {
var nodeList = document.querySelectorAll("[id^=select-meal-type]")
var values = Array.from(nodeList).map(val => val.value)
console.log(values);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br><br> type a number<input type="text" id="number">
<br><br>
<div id="container"></div>
<button onclick="getdata()">GET DATA</button>
<button onclick="getValues()">GET VALUES</button>
I have a drop down list and a button. I want to make the selection of list reflects on the button link.
Example JSFiddle
Here is the example code:
<select style="float:left;">
<option value="5">$5.00 monthly</option>
<option value="10">$10.00 monthly</option>
<option value="15">$15.00 monthly</option>
<option value="20">$20.00 monthly</option>
</select>
<div id="button" style="width:100px;height:30px;float:left;background:#ccc;line-height:30px;text-align:center;margin:auto 5px;">
Order
</div>
What I want to achieve is when the user for example selects the second option, the button link changes to http://ordernow/10/ instead of http://ordernow/5/ and so on. Can someone inform me how do that or provide a link for a tutorial regarding this? Thank you.
Using pure javascript and adding ids to some of the elements:
JSFiddle
Here's the JavaScript:
document.getElementById("subscription").onchange = function() {
document.getElementById("order-btn").href = "http://ordernow/"+this.value+"/";
}
You can listen to select's onchange to get the new selected option's value. And then add the value to button's href:
$('select').on('change', function () {
$('#button > a').attr('href', 'http://ordernow/' + $(this).val() + '/');
});
jsfiddle DEMO
Can use a regex to parse the end of the href so path doesn't need to be known
$('select').change(function(){
var val =$(this).val();
$('#button a').attr('href', function(_,href){
var reg = /\/\d\/$/;
return href.replace(reg, '/'+val+'/');
});
});
DEMO
Just wondering if someone can help me on a problem, I don't fully undersand why it doesn't work.
I have this fiddle, http://jsfiddle.net/uomt99zp/
What it is doing:
When you select from the drop down box, insert that word into the textarea.
Which it DOES, when the textarea isn't "touched".
If you type something into the box, and then try to select an item, it doesn't work.
I'm not sure why this doesn't update the textarea. Perhaps someone can shed some light on this issue?
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
You need to set value using .val():
$('.template').val($('.template').val()+text);
Working Demo 1
Also .val() can have callback function which can be used for setting a new value:
function
Type: Function( Integer index, String value ) => String
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
$('.template').val(function(i,v){ return v+ text});
Working Demo 2
You can try val(function) with old value + new text to append,
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').val(function(ind,val){
return val+text;
});
});
Live Demo
To answer to the "why" it does not work, it's because, the contents of a textarea represent its default value. So, when you append an element to the textarea, you change the default value of this textarea.
So it changes the textarea as long as you did not type in. Once you typed in, the default value is no more used, even if you remove all the text of the textarea.
By using .append you are just concatinating your output string if you want only the dropdown element it would be better to use the .text() or .val() method
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
var existing=$('.template').val();
$('.template').val(existing+text);
});
.append(), .html() and .text() methods do not work with form elements, for setting/getting value of a from element .val() method should be used instead:
Your code is working ...i tried it in visual studio .... Only change I had made is I kept the script under the option control... I am not sure about.for me its working fine.
<body >
<textarea name="template" required="required" class="template form-control" rows="6"></textarea>
<select class="templatesAvailableFields">
<option>Select One</option>
<option>Test1</option>
<option>Test2</option>
<option>Test3</option>
</select>
<script type="text/javascript">
$('.templatesAvailableFields').on('change', function () {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').append(text);
});
</script>
</body>
You should control input value's with val() method
// cache element
var $select = $('.templatesAvailableFields');
$select.change( function() {
$('.template').val($select[0].value);
});
just replace append with text
here is the updated fiddle
$('.templatesAvailableFields').on('change', function() {
var text = $('.templatesAvailableFields option:selected').text();
$('.template').text($('.template').text() + text);
// $('.template').val(text); this won't work in IE <= 7
});
http://jsfiddle.net/rrehan/uomt99zp/2/
I have a select list that's generated by the Javascript code of my app
<select name="addToContexts" id="addToContexts">
<option selected>private</option>
<option>public</option>
<option>shared</option>
</select>
What I need to do is that when the user performs a certain action the selected parameter shifts to another option, so that the result would be something like:
<select name="addToContexts" id="addToContexts">
<option>private</option>
<option selected>public</option>
<option>shared</option>
</select>
Do you know if there's a way to do it without regenerating the whole options list simply using jQuery to get the select element by ID and to change the selected option?
Thank you!
<body>
<select name="addToContexts" id="addToContexts">
<option selected>private</option>
<option>public</option>
<option>shared</option>
</select>
<button id="changeSelect">Change</button>
<script>
$("#changeSelect").click(function(){
$("#addToContexts option:nth-child(2)").prop("selected", true);
});
</script>
</body>
Something like this?
Hope this help.
http://jsfiddle.net/6Ljn1rzr/
$('input[type=checkbox]').on(
'change',
function() {
$('option').attr("selected",false);
$('option:contains(public)').attr("selected",true);
}
);
its very simple you can visit this thread
http://www.stackoverflow.com/questions/1314245/set-the-selected-index-of-a-dropdown-using-jquery
it has explained the in a very good manner and hopefully you will get your answer from this thread
http://jsfiddle.net/washington_guedes/ovpkLexj/5/
I used an ul-li "click" event as "certain action"... and it worked well
$("li").on("click", function(){
var aux = $(this/*li*/).html();
$('#addToContexts > option')
.prop("selected", false)
.each(function(){
if( $(this/*option*/).html() === aux){
$(this/*option*/).prop("selected", true);
}
});
});
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();
});