Add live text from input field to another div with Checkbox - javascript

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>');

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);
});

How to change the function to limit its action to the id, class or selector

I have a function written in jquery that copies the value of the checkbox to the textarea #msg
$(document).ready(function(){
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Clicking any checkbox on side copies of its value to the #msg field
How to reduce this effect that only checkboxes in the <ul> or a selected div operate in such a manner?
I want this:
<ul>
<input name="foo2" type="checkbox" value="Hello" id="tel_1">
<label for="tel_1">Hello</label>
</ul>
To be copied to the #msg textarea and this :
<input name="foo" value="123123123" id="tel_11" type="checkbox">
<label for="tel_11">Alan</label>
Not to be copied. I played with this :
$("input:checkbox").click(function()
And changed input:checkbox to ul:input:checkbox but I do not want to work.
You could use the id :
$(document).ready(function(){
$("#tel_1").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Or if you want to exclude just #tel_11 you could use :not() selector like :
$(document).ready(function(){
$("input:checkbox:not('#tel_11')").click(function() {
var output = "";
$("input:checked:not('#tel_11')").each(function() {
output += $(this).val() + "";
});
$("#msg").val(output.trim());
});
});
Update :
If you have several id's as you sain in the comment (answers example) you could use start with selector like $("[id^='answer_'") ans that will include all of your 18 answers, e.g :
$(document).ready(function(){
$("[id^='answer_'").click(function() {
var output = "";
output += $(this).val() + "";
$("#msg").val(output.trim());
});
});
Hope this helps.
Use a selector that just matches checkboxes that are children of <ul>.
$("ul > :checkbox").click(function() {
...
});

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);
})

How i can get value form select > option, jquery

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

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