bootstrap select picker not working with input field - javascript

I have a select picker and I need to make that, when select language from this select picker gets a value from select and put into input filed.
The problem is that when i get value is success but after get show alert empty. and put value empty in field.
$(".m_selectpicker").selectpicker();
$(document).on('change', '.changeLanguage', function () {
var selectedLanguage = $(this).val();
alert(selectedLanguage);
$(this).parents('.countries').find('.lang').attr('name', 'name' + '[' + selectedLanguage + ']');
});
language
English
Arabic
Turkey

You can update the value attribute as well, see here https://jsfiddle.net/Lq2fz7dg/
$(document).on('change', '.changeLanguage', function () {
var selectedLanguage = $(this).val();
alert(selectedLanguage);
$(this).parents('.countries').find('.lang').attr('name', 'name' + '[' + selectedLanguage + ']');
$(this).parents('.countries').find('.lang').attr('value', selectedLanguage);
});
Update
This will work when .selectpicker() is initialized:
$(".m_selectpicker").on("changed.bs.select",
function(e, clickedIndex, newValue, oldValue) {
$('.lang').attr('name', 'name' + '[' + this.value + ']');
$('.lang').attr('value', this.value);
});
https://jsfiddle.net/no0r3qjf/

Related

Getting selected radio button in JavaScript

I've tried lot's of solutions here before actually make this question but none of them has worked for me.
I've tried to use onclick handler, tried to get by input name, tried getElementId, tried elementClassName also i tried to loop them var i = 0, length = radios.length; i < length; i++ none has worked for me!
Logic
My radio buttons will append to view based on ajax action
I select any of this radio buttons
And i want get values of this selected radio button
Code
This is how my radios append I made it short to be clean and easy to read
success:function(data) {
$('.shipoptions').empty();
$('.shipoptionstitle').empty();
$('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
});
});
});
} //success function ends here
Now I want to get selected radio button values of data-code ,
data-service and value
For the temporary please just help me to get those values in console, later I'll fix the printing part myself.
Any idea?
<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">
var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');
var selectedVal= $("input:radio[name=postchoose]:checked").val();
SOLVED
$(function() {
$(".shipoptions").on('change', function(){
var radioValue = $("input[name='postchoose']:checked");
if(radioValue){
var val = radioValue.val();
var code = radioValue.data('code');
var service = radioValue.data('service');
alert("Your are a - " + code + "- " +service+ "- " +val);
}
});
});
I needed to get a higher class of my radio buttons .shipoptions
Try this jQuery Method.
$("input[type='radio']").click(function() {
var radioValue = $("input[name='postchoose']:checked").val();
var dataCode = $("input[name='postchoose']:checked").attr('data-code');
var dataService = $("input[name='gender']:checked").attr('data-service');
console.log(dataCode);
console.log(dataService);
console.log(radioValue);
});

jquery get first text element attribute from selected dropdown

both simple and complicate question:
I have my dropdown item created programmatically from ajax request and that is ok. So i serve name and surname for convenient aestetic way, but i need to send an ajax post with only surname and value is needed for other purposes.
$('#dropDocente').append('<option value="'+value.idDocente+'"">' + value.surname + ' ' + value.name +'</option>');
what i would achieve is:
var testd = $("#dropDocente option:selected").text();
console.log("Surname is : "+testd);
desired output == Surname is : Doe
so, in other hand, i would like get only first element of text in selected dropbox.
I can help me to understand how to reach my goal?
In jQuery, you don't use the .text() method to get the value of a dropdown menu. You need to just have:
var testd = $("#dropDocente").val();
and that will return the selected option's value from the dropdown.
you can add value.surname as a data-surname data tag onto the option and then retrieve that value by selecting the option and using .data('surname'). you can do this for any other value you want to single out as well
$(document).ready(function() {
var values = [
{ surname: "Doe", name: "John", idDocente: "some value here" },
{ surname: "Shmo", name: "John", idDocente: "some value here2" },
{ surname: "Little", name: "John", idDocente: "some value here3" },
];
for (var i = 0; i < values.length; i++) {
var value = values[i];
$('#dropDocente').append('<option value="'+value.idDocente+
'" data-surname="'+ value.surname +'">' + value.surname + ' '
+ value.name +'</option>');
}
// default first
$('.results').text($("#dropDocente option:first").data('surname') + ', ' + $("#dropDocente option:first").val());
// on change, get the surname
$('#dropDocente').on('change', function() {
$('.results').text($("#dropDocente option:selected").data('surname')+ ', ' + $("#dropDocente option:selected").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDocente">
</select>
<br/><br/><br/>
<div class="results">
</div>
You could just split full name on select change.
Something like this:
$('select').on('change', function(){
var id = $(this).val();
var fullName = $('select option:selected').text();
var surname = fullName.split(" ", 1);
});
Full example here: https://jsfiddle.net/1aj06Lw6/1/

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/

Passing variable name as id

I am appending the checkboxes in a particular class using some function.. I have a function to run everytime the checkbox is selected.. So I need to get the name and id of the Checkboxes..
Heres the part of the code where I am appending the checkbox dynamically.. Here value is the one I want the id and name attribute to be..
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' onclick='selectMainBrand(\"" + value + "\");' />" + value + "</label>");
});
set the id using
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append('<label class="checkbox"><input type="checkbox" id="' + value + '" onclick="selectMainBrand("' + value + '");" />' + value + '</label>');
});
function selectMainBrand(ids) {
$('#Brands').on("change", "input", function () {
console.log("called");
var selected = this.name;
console.log(selected);
});
}
I'm assuming your UL tag has id="brands". If not change the above code as follows
$('.fpblocks').on("change", "input", function () {
$.each(brandNameg, function(key, value) {
$(".fpblocks .fpblocksBrands_inner ul").append("<label class='checkbox'><input type='checkbox' id ='someID' name ='someName' />" + value + "</label>");
});
and on checkbox click..
$(".fpblocks .fpblocksBrands_inner ul :checkbox").live('click', function(){
var id = $(this).attr('id'); //get id of checked checkbox
var name = $(this).attr('name'); //get name of checked checkbox
})
remove onclick='selectMainBrand(value);' from inputs' generation code
After checkboxes are generated, you can select name and
$('#Brands input').on("change", function () {
var name=$(this).attr("name");
var id=$(this).attr("id");
alert(name);
alert(id);
console.log(selected);
});
see the DEMO http://jsfiddle.net/BbtEG/
Your dynamically created html (<input type='checkbox' onclick='selectMainBrand(value);' />) does not have a name, or an id. You cannot pass what doesn't exist. To solve this, generate a name and an id to use.
Also in your selectMainBrand function you don't appear to be using the ids parameter that you're passing in. All that function is doing is binding a handler to the input which, since you're using on to bind it, seems silly.
Why not use on to delegate the handler instead? If you delegate the handler, you can grab the name or id from within the handler thereby obviating the need to pass those in as parameters (working demo).
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
//delegate the change handler
$('.fpblocks .fpblocksBrands_inner').on("change", '#Brands input', function (e) {
var selectedName = this.name,
selectedId = this.id,
isChecked = this.checked;
console.log(JSON.stringify({
"called": true,
"selectedName": selectedName,
"selectedId": selectedId,
"isChecked": isChecked
}));
});
If you truly have your heart set on passing in the parameters, there are ways to do that, such as binding the handler within the loop where you create the inputs (working demo):
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key //set the id, appending the key to make it unique
}).click(function (e) {
var self = $(this), // capture the input as a jQuery object (typically very useful)
actualHandler = function (id, name) {
// do stuff
console.log(JSON.stringify({
"called": "actualHandler",
"selectedName": id,
"selectedId": name,
"isChecked": self.prop('checked')
}));
};
actualHandler(this.id, this.name);
// or
actualHandler(self.attr('id'), self.attr('name'));
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
or you could set the onchange attribute in the loop where you create the inputs (working demo):
window.inputHandler = function (id, name) { // must be added to the global scope, otherwise it won't be visible.
// do stuff
console.log(JSON.stringify({
"called": "inputHandler",
"selectedName": id,
"selectedId": name
}));
};
$.each(brandNameg, function (key, value) {
var label = $('<label />').addClass('checkbox'),
input = $('<input />').attr({
"type": "checkbox",
"name": "mainBrand" + key, //set the name, appending the key to make it unique
"id": "mainBrand" + key, //set the id, appending the key to make it unique
"onchange": "inputHandler('" + "mainBrand" + key + "', '" + "mainBrand" + key + "')"
});
$(".fpblocks .fpblocksBrands_inner ul").append(label.append(input).append(value));
});
and there are other ways to go about it.
Personally, I would use the delegation.

Categories