Is there a way to get the value from a div element to textbox?
My script codes
$(document).ready(function() {
barcode.setHandler(function(barcode) {
$('#result').html(barcode);
});
barcode.init();
I show the result with the following code
<div id="result"></div>
I fail to get the div value into the textBox.
<input type="text" id="result">
To achieve expected result, use below option
Avoid using same id for multiple elements , instead of that use class or two different ids or use one as class and for other use as id
$(document).ready(function() {
console.log( $('#result').text())
$('.result').val( $('#result').text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">1222</div>
<input type="text" class="result">
code sample - https://codepen.io/nagasai/pen/yjomXp
Ids need to be unique on a given page; your input and div both have the same id. To insert from the div to the input, first get the text inside the div, then apply that to the input using .val().
const foo = $('#foo').text();
$('#bar').val(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
This is inside the div
</div>
<input type="text" id="bar"></input>
Related
I have a list of divs on a page. I have a filter system that fills in a 'data-' element with a possible list of values.
Example:
<div data-myvalues="value1,value2,value3"></div>
<div data-myvalues="value2,value3"></div>
<div data-myvalues="value1,value2"></div>
<div data-myvalues="value1,value3"></div>
Then I have some jQuery that tries to filter based on some selections that include the values in the data-myvalues attribute. However, the jQuery filter does not quite work because I think it sees the values as including the comma (,) in the value.
How, in jQuery, would I filter based on an if the divs include the values or not. I am currently using the jQuery
$("div[data-myvalue*='value1']").show();
But it seems to now quite work for some reason it will work if the data-myvalues only has one value in it, the jQuery works, but if there are multiples separated by a comma, the jQuery does not work.
I have a JS fiddle here with a simple sample code I was messing with to get the proof of concept to work.
https://jsfiddle.net/ebz3cmjn/1/
Is there a better way to list values on an element then filter them?
Thanks in advance.
You can try something like this:
$(document).ready(function() {
$.each($('div'), function(i, v){
var values = $(v).data('myvalues');
if(values.indexOf('value1') != -1) {
$(v).show();
} else {
$(v).hide();
}
})
});
And html content with data values:
<div data-myvalues="value1,value2,value3"></div>
<div data-myvalues="value2,value3"></div>
<div data-myvalues="value1,value2"></div>
<div data-myvalues="value1,value3"></div>
Hope this helps.
The data attribute takes JSON object which you can take advantage of.
Given the following element:
<input data-nations='["anothernation", "nationman", "country"]' type="text" value="Germany">
You could filter the desired elements based on the target value:
var targetNation = "nationman";
$("input[data-nations]")
.filter(function () {
// Returns the list as array
return $(this).data("nations").indexOf(targetNation) > -1;
})
.css("background-color", "blue");
Note the two differences between the quotes:
// will parse correctly
data-nations='["anothernation", "nationman", "country"]'
// will NOT parse correctly since it will be treated as plain text
data-nations="['anothernation', 'nationman', 'country']"
Try with .not() like the following way:
$(document).ready(function(){
$("input[data-me*='nationman']").css("background-color", "yellow");
$("input").not("[data-me*='nationman']").css("background-color", "red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-me="nationality" type="text" value="Chinese">
<input data-me="nationman" type="text" value="English">
<!--This doesn't work with more than one value-->
<input data-me="nationman,country" type="text" value="Germany">
<input data-me="anothernation" type="text" value="Norwegian">
<p>This selector selects all input fields with the attribute name that contains the string 'nation'.</p>
You can also loop through all elements with .each():
$(document).ready(function() {
$('[data-myvalues]').each(function(){
var values = $(this).data('myvalues');
if(values.includes('value1'))
$(this).show();
else
$(this).hide();
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-myvalues="value1,value2,value3">value1,value2,value3</div>
<div data-myvalues="value2,value3">value2,value3</div>
<div data-myvalues="value1,value2">value1,value2</div>
<div data-myvalues="value1,value3">value1,value3</div>
Checkout the snippet;
I have modified you code a litte bit, hope this will help to get your answer;
This is a little bit tricky answer, but you can easily understand the code
$(document).ready(function(){
var el = $('input');
el.each(item =>{
var attr = el[item].dataset
if(attr.me.match(/nationman/)){
el[item].setAttribute('style', 'background-color:yellow')
}else{
el[item].setAttribute('style', 'background-color:red')
}
})
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input data-me="nationality" type="text" value="Chinese">
<input data-me="nationman" type="text" value="English">
<!--This doesn't work with more than one value-->
<input data-me="nationman, country" type="text" value="Germany">
<input data-me="anothernation" type="text" value="Norwegian">
<p>This selector selects all input fields with the attribute name that contains the string 'nation'.</p>
</body>
</html>
Try This I think it will work
$(document).ready(function(){
$("input[data-me*='nationman']").css("background-color", "yellow");
$("input").not("[data-me*='nationman']").css("background-color", "red");
});
I have simple textboxes generated by AJAX.
<input type='text' id='txt1' name='txt1_nm' />
What I'd like to do, when I press a button. The input is all copied inside a different div with its new value inserted by user.
I use
$('#txt1').html();
but, the value is not copied only the textbox
You need to make use of clone() so that you get the element with its value. Type anything in the textbox in the snippet below and press the Copy button.
//detect the click of the copy button
$('#copyBtn').click(function(){
//get the clonned element
var inputElement = $('#txt1').clone();
//add clonned element to a new div
$('#copiedDiv').html(inputElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='text' id='txt1' name='txt1_nm' />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>
If you want to add multiple cloned items then you will require to change the id of the input element and then append that to the page. You can do like this to achieve it,
//detect the click of the copy button
$('#copyBtn').click(function(){
//get the last input item
var $inputEl = $('input[name="txt1_nm"]:last');
//get the next id number
var num = parseInt( $inputEl.prop("id").match(/\d+/g), 10 ) +1;
//clone and set a new id for this element
var $cloneEl = $inputEl.clone().prop('id', 'txt'+num );
//add clonned element to a new div
$('#copiedDiv').append($cloneEl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type='text' id='txt1' name='txt1_nm' />
</div>
<div id='copiedDiv'></div>
<button id='copyBtn'>Copy</button>
$(document).on('click','#myBtn',function(){
value=$('#txt1').val();
$('#myDiv').empty();
$('#myDiv').append($('#txt1').clone());
$('#txt1').val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='txt1' name='txt1_nm' />
<button type="button" id="myBtn">Click Me</button>
<div id="myDiv"></div>
You can simply use:
$('#txt1').clone()
It will perform a deep clone of that element with all of its content.
NOTE: Cloning an element will also duplicate its ID if it has one.
You should change any ids to classes beforehand.
This is from the documentation:
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
I want to append a duplicate of an input box in a parent box. Here is my HTML structure:
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
And here is my jQuery code:
function addPlaceholder(parentClass){
var placeHolder = $(parentClass).children().eq(0);
$(parentClass).append(placeHolder);
console.log(placeHolder);
}
$('.add-reading-btn').click(function(){
addPlaceholder('.reading-group');
});
Here is the jsfiddle link: https://jsfiddle.net/abhishekraj007/kexe6gxn/
What am I doing wrong?
Your code is taking the existing <input> element and moving it from the <div> and back into the <div>, so it looks like nothing is happening. If you .clone() the element and then .append() it, a new element will be added.
Here is a working example:
function addPlaceholder(parentClass) {
var placeHolder = $(parentClass).children().eq(0).clone();
$(parentClass).append(placeHolder);
console.log(placeHolder);
}
$('.add-reading-btn').click(function() {
addPlaceholder('.reading-group');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
If you want to add focus to your <input> element on load, you can do so by adding this line to the bottom of your code:
$('#link').focus();
If you want to add focus to the new element on creation, as well as give it an empty value rather than copying the prior element's value, add this line to the end of your addPlaceholder() function:
$(placeHolder).val("").focus();
you can just add the .clone() method of jquery to create a clone of the textbox like below . You were only referring to the same element not the cloned html before.
$(document).ready(function(){
function addPlaceholder(parentClass){
var placeHolder = $(parentClass).children().eq(0).clone();
$(parentClass).append(placeHolder);
//console.log(placeHolder);
}
$('.add-reading-btn').click(function(){
addPlaceholder('.reading-group');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="reading-group input-group">
<input type="text" placeholder="Enter Reading link" id="link">
</div>
+ Add another link
Here is a working fiddle
https://jsfiddle.net/kexe6gxn/2/
I am a beginner in programming and am stuck in a problem. I want to find the last child (element) of parent (form). Then I want to insert an input element after the last child but it should be inside the form not after the form (outside). The form might contain input elements as well as select elements. How to accomplish it? I have tried the following ways but they don't work unfortunately.
var lastRepeatingGroup = $('.form-to-be-submitted:last'); // this one gives me the whole form meaning if I add something it will added at the end of the form
var lastRepeatingGroup = $('.form-to-be-submitted input:last'); //this gives me the last input element
var lastRepeatingGroup = $('.form-to-be-submitted input select').last(); //this does nothing, I think its an error
$newSection = $('<input type="button" value="newbutton" name="mybutton"/>');
newSection.insertAfter(lastRepeatingGroup); // when I use this statement it adds after the form not inside the form
So you just need some guidance on CSS Selectors and Jquery methods.
First lets look at:
The form might contain input elements as well as select elements.
So in CSS to do an or you need to use a comma:
input,select
if you are looking for direct descendants you need to use a >
form > input, form > select
These are then wrapped in jquery:
$('form > input, form > select')
Which yields all items, so we use last() to grab the last element:
var $last = $('form > input, form > select').last();
(if you don't need the > just remove it).
This was pretty close:
var lastRepeatingGroup = $('.form-to-be-submitted input select').last();
but it's looking for a select element in a input element in that class. Just needs a little adjustment:
var lastRepeatingGroup = $('.form-to-be-submitted input, .form-to-be-submitted select')
.last();
If you want to insert the element at the end of a specific element, you don't need to find the last item. Just use jquery's append
Except:
Consider the following HTML:
<h2>Greetings</h2>
<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
</div>
You can create content and insert it into several elements at once:
$( ".inner" ).append( "<p>Test</p>" );
Each inner element gets this new content:
<h2>Greetings</h2>
<div class="container">
<div class="inner">
Hello
<p>Test</p>
</div>
<div class="inner">
Goodbye
<p>Test</p>
</div>
</div>
This should work:
$('.form-to-be-submitted').children().last()
.children() will select all the children in your form and .last() filters that further to only select the last child.
And to insert content after that element, just use .after() like:
$('.form-to-be-submitted').children().last().after('<input>')
Example:
$('.form-to-be-submitted').children().last().after('<input type="radio">')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-to-be-submitted">
<input type="text">
<input type="radio">
<input type="checkbox">
<select>
<option></option>
</select>
</form>
JQuery not needed. To insert a new element just before the end of the form, simply use .appendChild().
var frm = document.getElementById("theForm"); // Get reference to form
// Create a new element and configure it
var newElement = document.createElement("input");
newElement.id = "txtUser";
// Simply append it to the form.
frm.appendChild(newElement);
console.log(frm.elements[frm.elements.length-1]); // Get last element in form
<form id="theForm">
<input type="text">
<select>
<option>one</option>
<option>two</option>
<option>three</option>
</select>
<button type="button">Click Me</button>
</form>
I have structure like this. On button click jquery code make border of input red if field is empty. Everything works fine with first row. At others row border become red after button click even if i put valid value.
$('.btn-submit').click(function(){
var value = $(':input').val();
if(!value.length) {
$(this).parents('.row').find(':input').css('border-color','#f00');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
Change you JS-Code:
$('.btn-submit').click(function(){
var value = $(this).parent().find('input').val();
if(!value.length) {
$(this).parents('.row').find(':input').css('border-color','#f00');
}
});
Your Issue:
You select all <inputs/> instead of the closest.
When any button is clicked, it is checking the value of the first <input>.
Change this line:
var value = $(':input').val();
To this:
var value = $(this).prev(":input").val();
This should select the <input> element directly before the button.
Another tip: You seem to try to find the child input of the parent using jQuery. Instead, you can find the sibling, using something like prev() (which will work in your case).
Try this:
$('.btn-submit').click(function(){
var value = $(this).parent().find("input").val();
if(!value.length) {
$(this).parent().find(':input').css('border-color','#f00');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='row'>
<input>
<button class='btn-submit'></button>
</div>
<div class='row'>
<input>
<button class='btn-submit'></button>
</div>
<div class='row'>
<input>
<button class='btn-submit'></button>
</div>
Your problem is that you are looking at all the inputs not just the sibling of the button.
Try this javascript instead:
$('.btn-submit').click(function(){
var value = $(this).parent().find('input').val();
if(!value.length) {
$(this).parents('.row').find(':input').css('border-color','#f00');
}
});
Here is the fiddle