How i can get value form select > option, jquery - javascript

I have a problem with get value form select > option.
I make option that:
$.each(response, function(i, element)
{
var nazwaKategori = element.name;
var idKategori = element.id;
$("#kategoria").append("<option>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
});
In body:
<form role="form">
<div class="form-group">
<label align="center" for="text">Lista dostępnych kategorii.</label>
<select class="form-control" id="kategoria">
<div id="kategoria">
</div>
</select>
<div id="wypisz"><div>
</div>
</form>
And i get this option:
<script>
$( "#kategoria" ).change(function () {
var str = "";
$( "#kategoria option:selected" ).each(function() {
str += $(this.KategoriaID).val() + " ";
});
$( "#wypisz" ).text( str );
})
.change();
</script>
How i can get only idKategori ? I musc find pattern in get text?
Thanks

Well apart of having a wrong html structure with a div inside a select, when you are creating your dropdown, you could use something like this:
$("#kategoria").append("<option value='"+idKategori+"'>KategoriaID:" + idKategori + ", Nazwa Kategorii:" + nazwaKategori + "</option>");
So every option will have a value and then in the change event you could use this:
$( "#kategoria" ).on("change", function () {
var optionselected = $(this).find(":selected").val();
//HEre you will have you value of the option selected in a variable
console.log(optionselected);
});
I don't know if thats what you wanted, and I don't know if your dropdown creation is working, but your questions is to get value from select option with jquery. Hope this helps

Related

How to create a enhanced HTML TransferBox with an attribute

I need to create an enhanced transferbox, using HTML, JavaScript and JQuery.
I have a set of options a user can select from and associate with an attribute. The selection and deselection must be accomplished with two SELECT HTML elements (i.e., a transferbox). For example, these options can be a list of skill names.
When the 'add' button is clicked, the option(s) selected in the first SELECT element, along with an attribute (e.g. number of years from a text box) must be transferred from the source SELECT element to selected/destination SELECT element. The attribute must be displayed along with the item text in this second SELECT element (for example, the item displays the skill and the number of years).
When the 'remove' button is clicked, the selected option(s) in the second SELECT element must be moved back to the first SELECT element (in the original format .. without the attribute).
JSON should be the data format for initial selection setup and saving latest selections.
I want an initial set of selections and attributes to be set via JSON in an a hidden input field. I want the final set of selections to be saved to JSON in the same hidden input field.
Example HTML:
<input type="hidden" id="SelectionsId" value='[{ "id": "2", "attribute":"15"},{ "id": "4", "attribute":"3" }]' />
<!--<input type="hidden" id="SelectionsId" value='[]' />-->
<div>
<select class="MultiSelect" multiple="multiple" id="SelectFromId">
<option value="1">.NET</option>
<option value="2">C#</option>
<option value="3">SQL Server</option>
<option value="4">jQuery</option>
<option value="5">Oracle</option>
<option value="6">WPF</option>
</select>
<div style="float:left; margin-top:3%; padding:8px;">
<div>
<span>Years:</span>
<input id="YearsId" type="number" value="1" style="width:36px;" />
<button title="Add selected" id="includeBtnId">⇾</button>
</div>
<div style="text-align:center;margin-top:16%;">
<button title="Remove selected" id="removeBtnId">⇽</button>
</div>
</div>
<select class="MultiSelect" multiple="multiple" id="SelectToId"></select>
</div>
<div style="clear:both;"></div>
<div style="margin-top:40px;margin-left:200px;">
<button onclick="SaveFinalSelections();">Save</button>
</div>
Example CSS:
<style>
.MultiSelect {
width: 200px;
height: 200px;
float: left;
}
</style>
Visual of requirement:
Here's a solution to the challenge. The variables being setup at the start make this solution easy to configure and maintain.
When the page gets displayed, the SetupInitialSelections method looks at the JSON data in the hidden input field and populates the selected items.
When the 'Save' button clicked, the current selections are converted to JSON and placed back in the hidden input field.
Invisible character \u200C is introduced to delimit the item text and the attribute during display. This comes in to use if the item has to be removed and the original item text has to be determined so it can be placed back in the source SELECT element.
The selectNewItem variable can be set to true if you would like the newly added item to be selected soon after adding it to the SELECT element via the 'add' or 'remove' operations.
This solution supports multiple item selections. So multiple items can be added at once ... and similarly multiple items can be removed at once.
<script src="jquery-1.12.4.js"></script>
<script>
var savedSelectionsId = 'SelectionsId';
var fromElementId = 'SelectFromId';
var toElementId = 'SelectToId';
var includeButtonId = 'includeBtnId';
var removeButtonId = 'removeBtnId';
var extraElementId = 'YearsId';
var extraPrefix = " (";
var extraSuffix = " years)";
var noItemsToIncludeMessage = 'Select item(s) to include.';
var noItemsToRemoveMessage = 'Select item(s) to remove.';
var selectNewItem = false;
var hiddenSeparator = '\u200C'; // invisible seperator character
$(document).ready(function () {
SetupInitialSelections();
//when button clicked, include selected item(s)
$("#" + includeButtonId).click(function (e) {
var selectedOpts = $('#' + fromElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToIncludeMessage);
e.preventDefault();
return;
}
var attribute = $("#" + extraElementId).val();
selectedOpts.each(function () {
var newItem = $('<option>', { value: $(this).val(), text: $(this).text() + hiddenSeparator + extraPrefix + attribute + extraSuffix });
$('#' + toElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
//when button clicked, remove selected item(s)
$("#" + removeButtonId).click(function (e) {
var selectedOpts = $('#' + toElementId + ' option:selected');
if (selectedOpts.length == 0) {
alert(noItemsToRemoveMessage);
e.preventDefault();
return;
}
selectedOpts.each(function () {
var textComponents = $(this).text().split(hiddenSeparator);
var textOnly = textComponents[0];
var newItem = $('<option>', { value: $(this).val(), text: textOnly });
$('#' + fromElementId).append(newItem);
if (selectNewItem) {
newItem.prop('selected', true);
}
});
$(selectedOpts).remove();
e.preventDefault();
});
});
// Setup/load initial selections
function SetupInitialSelections() {
var data = jQuery.parseJSON($("#" + savedSelectionsId).val());
$.each(data, function (id, item) {
var sourceItem = $("#" + fromElementId + " option[value='" + item.id + "']");
var newText = sourceItem.text() + hiddenSeparator + extraPrefix + item.attribute + extraSuffix;
$("#" + toElementId).append($("<option>", { value: sourceItem.val(), text: newText }));
sourceItem.remove();
});
}
// Save final selections
function SaveFinalSelections() {
var selectedItems = $("#" + toElementId + " option");
var values = $.map(selectedItems, function (option) {
var textComponents = option.text.split(hiddenSeparator);
var attribute = textComponents[1].substring(extraPrefix.length);
var attribute = attribute.substring(0, attribute.length - extraSuffix.length);
return '{"id":"' + option.value + '","attribute":"' + attribute + '"}';
});
$("#" + savedSelectionsId).val("[" + values + "]");
}
</script>

jQuery get data-name as value

I was previously using
jQuery( "select#colour option:selected" ).each(function() {
value += "colour-" + jQuery( this ).val();
});
This took the selected value from a dropdown and constructed another value with it.
I am now trying to modify this to get the value (data-name) from the following html...
<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">
Anyone got an similar example they can point me at?
use .data('name') to get the data-name attribute value
$(document).ready(function() {
$('.select-option').each(function() {
var name = $(this).data('name');
console.log(name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-option" data-name="apple">
<div class="select-option selected" data-name="orange">
<div class="select-option" data-name="banana">
var value;
$('.select-option').each(function(){
value+=$(this).attr('data-name'); //or $(this).data('name');
});
Use .data()
jQuery( ".select-option" ).each(function() {
value += "colour-" + jQuery( this ).data("name");
})

Replace href on select change

I have a select element with options with values that are some numbers (some id's).
<select id="select">
<option value="21">Random<option>
<option value="23">Random 2<option>
<option value="25">Random 3<option>
<option value="27">Random 4<option>
</select>
Next to it is a submit button that will preform some kind of submit.
<a class="button" href="www.random.org">Click me!</a>
I need to add the ?id= to that link, with the id value of the select. I created the code, but the issue is that it just appends the ?id= every time I change the select the option
var id;
$('#select').on('change', function(){
id = $(this).val();
var new_href = $('.button').attr('href') + '?id=' + id;
$('.button').attr('href', new_href);
});
So when I click on first option I get, for the href
www.random.org?id=21
But if I click on second one (or any for that matter) I get
www.random.org?id=21?id=23
It appends the id. How to 'clear' the previous id on change, and replace with the selected one? What am I doing wrong?
This should work.
var id;
var original_link = "www.random.org";
$('#select').on('change', function(){
$('.button').attr('href', original_link);
id = $(this).val();
var new_href = $('.button').attr('href') + '?id=' + id;
$('.button').attr('href', new_href);
});
you can try like this change button link
<a class="button" href="www.random.org" data-link="www.random.org">Click me!</a>
and change javascript like this
var id;
$('#select').on('change', function(){
id = $(this).val();
var new_href = $('.button').data('link') + '?id=' + id;
$('.button').attr('href', new_href);
});
I think it's helpful to you.
You can pass to .attr function as second argument, where you can replace url for .button, like so
$('#select').on('change', function(){
var id = $(this).val();
$('.button').attr('href', function (index, value) {
// if there is id in url - replace it, else add id to url
return /\?id=/.test(value) ? value.replace(/id=(\d+)/, 'id=' + id) : (value + '?id=' + id);
});
});
Example
Respecting every other answer, I would prefer a small amount of code:
$('#select').on('change', function(){
$( '.button' ).attr( 'href', $( '.button' ).attr( 'href' ).split( '?id=' )[0] + '?id=' + $( this ).val() );
});
This code actually splits the href when a ?id= exists and gives you only the part before it. When there is no ?id= than you get the normal href and after this, you just add ?id= and $( this ).val() to the href. (It's already in the code that I wrote)
That's it. No RegEx, Wordarounds or more lines of code than needed.
$target = $(".target");
$button = $(".button");
With jQuery you can $target.attr('href', $button.data('href-url') + '?id=' + id))
Check this
Demo
$('#select').on('change', function() {
var aLink = $('.button'),
selVal = $(this).val(),
staticLink = "www.random.org";
//alert(selVal)
$(aLink).attr('href', staticLink + "?id=" + selVal);
})

Add live text from input field to another div with Checkbox

I have an input field with Add button below it. Also have another Div class named .new-option-content
What I am trying to do is if anyone type something in the input filed and click the +ADD button this text of the input filed will append with a Check box inside .new-option-content div.
Here is the Fiddle
I tried with this but I guess with this process I can't get the result.
$( ".checklist-new-item-text" )
.keyup(function() {
var value = $( this ).val();
$( ".new-option-content" ).text( value );
})
.keyup();
I am not good with advance jquery. I did tried to find something similar but failed. I am not sure if this can be done with jquery.
Any help or suggestion will be appreciated.
$("#add").click(function(){
var newLabel = $("#optionInput").val();
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
$(".new-option-content").append(newOption);
$("#optionInput").val(''); //clearing value
})
Fiddle: http://jsfiddle.net/has9L9Lh/8/
If you want to use it in multiple places on your page, you can try this modified version:
$(".new-option-add").click(function(){
var labelInput = $(this).parent().parent().find(".checklist-new-item-text")
var newLabel = labelInput.val()
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
// where to append?
var listToAppend = $(this).attr("data")
$("." + listToAppend).append(newOption);
labelInput.val(''); //clearing value
})
We are using data attribute value on the button, to assign class name of the list, which need to be updated.
Fiddle: http://jsfiddle.net/has9L9Lh/18/
Here is how you can do it:
$(function() {
$('.new-option-add').on('click',function() {
var noc = $('.new-option-content'),
val = $('.checklist-new-item-text');
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
And this should work for multiple sections:
$(function() {
$('.new-option-add').on('click',function() {
var section = $(this).closest('section'),
noc = $('.new-option-content', section),
val = $('.checklist-new-item-text', section);
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
Many have answered, yet another option is to use .clone(), cause otherwise you can end up in a maintainence nightmare, so something like
$(".new-option-add").click(function() {
var checkbox = $(".checkbox:first").clone(), value;
value = $(".checklist-new-item-text").val();
checkbox.html(checkbox.html().replace('Sample 1', value));
checkbox.appendTo($(".new-option-content"));
})
http://jsfiddle.net/has9L9Lh/19/
you can do this by adding this code
on click event
$('#yourDiv').append(' <label><input id="chkbox" type="checkbox"> "+$('#yourText').val() +" </label>');

Javascript/jquery write each text value from :selected option to separate input

I'm retrieving some data from MySQL and write it in certain select tags, then i retrieve every selected option value and display it in a DIV, here is the javascript:
function main() {
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div#one").text(str);
})
.trigger('change');
}
So, i want each retrieved value to be written in separate input:
First value: <input type="text" id="test" />
Second value: <input type="text" id="test2" />
Third value: <input type="text" id="test3" />
How can i do that? Many thanks!
Simple select always have a selected value, so you can try something like this:
$(function() {
$("select").change(function() {
var str = "";
$("select").each(function() {
str += $(this).val()+"<br/>";
});
$("div#one").html(str);
});
});
You can see in action here: http://jsfiddle.net/vJdUt/
For adding the selected options in a "div" tag:
//empty div at start using .empty()
$("select").change(function () {
//get the selected option's text and store it in map
var map = $("select :selected").map(function () {
var txt = $(this).text();
//do not add the value to map[] if the chosen value begins with "Select"
return txt.indexOf("Select") === -1 ? txt + " , " : "";
}).get();
//add it to div
$("#one").html(map);
});
For adding the selected options in an "input" tag:
//empty textboxes at start using .val("")
$("select").change(function () {
var text = $(":selected", this).text() //this.value;
//get the index of the select box chosen
var index = $(this).index();
//get the correct text box corresponding to chosen select
var $input = $("input[type=text]").eq(index);
//set the value for the input
$input.val(function () {
//do not add the value to text box if the chosen value begins with "Select"
return text.indexOf("Select") === -1 ? text : "";
});
});
Consolidated demo
http://jsfiddle.net/hungerpain/kaXjX/

Categories