Create array from TextArea using jquery - javascript

I have the following code
<!----SUBMIT BUTTON---->
<input type="button" value="Submit" onClick="getData();">
.....
<div id="rev"></div>
After click on the submit button, I can be able to display my required data from my database within the text area with id='rev' in the format below:
20
30
I want to push these content of the text area into an array using jquery
<script type="text/javascript">
var arr=new Array();
function createArr()
{
var txt=$('#rev').val();
$.each(txt.split('\n'),function(i,value){
if(value!=""){
arr.push(value);
}
});
}
createArr();
document.write(arr[0]);
</script>
It seems does not work, the output on my webpage suppose to display the first element of my array which is 20. Any one can show me what did I do wrong with my code ?
It works when I changed this
<div id="rev"></div>
into
<textarea id="rev"></textarea>.
I dont know why div can not be used here ?

Wrap your entire function using window.onload function.Try this:
<script type="text/javascript">
window.onload = function(){
function createArr()
{
var arr=new Array();
var txt=$('#rev').html(); // use html() instead of val()
$.each(txt.split('\n'),function(i,value){
if(value!=""){
arr.push(value);
}
});
}
createArr();
console.log(arr[0]);
}
</script>
Demo

I think it is beause you output only the first one:
document.write(arr[0]);
Maybe you need this?
$.each(arr, function(i, val) {
document.write(val);
}

Related

Adding localstorage array

I'm having hard time on this localstorage array. I have search it here but can't get it out. Hope you can help me with this one.
Here is my code.
$(function(){
var addWishlist = $('.add-wishlist');
addWishlist.click(function(e){
e.preventDefault();
var product_ids = [];
localStorage.setItem('product_ids', $(this).prev().val() );
console.log( localStorage.getItem('product_ids') );
});
});
The output is:
The output should be [2, 3, 4, 1]
You need to add it to array on button click and then store it to local storage. Also product_ids should be initialized outside the click event
var product_ids = [];
addWishlist.click(function(e){
e.preventDefault();
product_ids.push($(this).prev().val())
localStorage.setItem('product_ids',product_ids );
console.log(localStorage.getItem('product_ids') );
});
There a couple of things wrong:
The array product_ids is always empty because you need to push() or unshift(), or anything to fill the array.
localStorage can only take strings, I don't even think it will even recognize your empty array.
Changes
Added an extra button to load the data into localStorage
Text is entered then click the Add button.
The value of the text input is push()ed into the array productList.
Each time productList is updated, it is stored in a hidden input #cache
When the Done button is clicked, the value of #cache is converted into a string by JSON.stringify.
Once productList is a string, it is then stored in localStorageand is displayed in #output.
Due to SO sandbox, the Snippet doesn't work, so review this PLUNKER instead.
SNIPPET
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<fieldset>
<legend>wishList</legend>
<input id='in1'>
<button><a href='#' id='add'>Add</a>
</button>
<button><a href='#' id='done'>Done</a>
</button>
<label for='out1'>wishList:</label>
<output id='out1'></output>
<input id='cache' type='hidden'>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
var productList = [];
$('#add').on('click', function(e) {
e.preventDefault();
var productItem = $('#in1').val();
productList.push(productItem);
$('#cache').val(productList);
});
$('#done').on('click', function(e) {
e.preventDefault();
var cached = $('#cache').val();
var str = JSON.stringify(cached);
localStorage.setItem('proList', str);
var stored = localStorage.getItem('proList');
console.log(stored)
$('#out1').html(stored);
});
});
</script>
</body>
</html>

How to print multiple html tags in jquery

How to print the multiple input boxes using jquery
I am using the following code
<script type="text/javascript">
$(document).ready(function(){
$("#taxId").change(function(){
var tax_id=$("#taxId").val();
$.ajax({
type:"post",
url:"<?php echo base_url();?>index.php/pranasInventory/get_tax_detail",
data:{tax_id:tax_id},
success:function(data)
{
var json_obj = $.parseJSON(data);//parse JSON
var len=json_obj.length;
for (var i=0;i<len;i++)
{
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
}
});
});
});
</script>
It print only one input tag.
my console message like this
Service tax # 14%<input id='taxcal' name='taxcal' placeholder='0.00'>
swachh bharat cess # 0.5%<input id='taxcal' name='taxcal'placeholder='0.00'>
I want print two input box.
please help me
The html function replaces the whole content.
You might replace
var len=json_obj.length;
for (var i=0;i<len;i++) {
var output=json_obj[i].tax_detail+"<input id='taxcal' name='taxcal' placeholder='0.00'>";
$('#taxDetail').html(output);
console.log(output);
}
with
$('#taxDetail').append(json_obj.map(function(obj){
return $("<input placeholder='0.00'>");
});
but you need to decide how to handle the ids of the added inputs as you can't obviously use the same for all.
.html replaces the whole content of the div. You must use JQuery append or prepend methods.

jQuery: get clicked button values

I need to get the values of a jQuery button when a form is submitted. The form and jQuery i'm using is below, but it's not working.
I need to get the value of data-url.
jQuery code
$("#addAgency").submit(function(event) {
var val = $("button[type=submit][clicked=true]").attr('data-url');
alert(val);
});
HTML Code
<form id="addAgency">
<button type="submit" data-url="test.php">
</form>
Thanks in advance.
try
$("#addAgency").submit(function(event) {
var val = $(this).find("button[type=submit]").data('url');
alert(val);
});
I have never heard of the [clicked=true] and I don't think that is right. The following will find the button from the children of the submitted form.
$("#addAgency").submit(function(event) {
var val = $(this).find('button[type=submit]').attr('data-url');
alert(val);
});
Try this.
$("#addAgency").submit(function(event) {
alert($(event.target).find('button').data('url'));
});
https://jsfiddle.net/t3y5x6ej/2/

How can i get my string replace with to equal the value of a form input?

Im trying to use string replace to change a line of code within my page.
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith ='??????????';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>
How can I get my...
var replaceWith ='??????????';
...to equal the value of an input from a form on the page?
Note the input value is auto populated on page load and the user does not enter in there own email address.
I assume you have an input such as <input id="inputValue" type="text" />
The general approach is to use a DOM function like getElementById() or querySelector(), and access its value with the value property.
Your code could be as simple as:
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith = document.getElementById('inputValue').value;
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

Best way to pass JS/ css info to a form

I am sure this is so easy and I'm just a huge huge noob. I have a form on a PHP page, and it has a few normal form elements (1 textarea, 1 text field).
I am also dynamically adding 100 small images to the page, which are random, and I am using JQuery to let someone select or deselect these images:
Here is the html that loops 100 times to display the images:
<div class='avatar'><img class='avatar_image' src='$this_profile_image' name='$thisfriend'></div>
and here is the Jquery:
<script type="text/javascript">
$(document).ready(function() {
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
});
</script>
What I want to do is, when the form is submitted, have the script that processes it be able to tell which of those 100 images is selected (so it's class will be "red" instead of "avatar_image"). I am blanking on this.
You'll need to add hidden inputs with some kind of identifiers for those images, and toggle the state of those inputs based on the image selected-ness. Something like this:
Change your image markup:
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend'>
<input type="hidden" name="avatar_image[]" value="$this_profile_image" disabled="disabled" />
</div>
Change jQuery binding (and use event delegation, maybe pick a better container than document.body):
<script type="text/javascript">
$(function() {
var selClass = 'red';
$(document.body).on('click', ".avatar_image", function() {
var $this = $(this);
var $inp = $this.siblings('input[type="hidden"]');
var isSelected = $this.hasClass(selClass), willBeSelected = !isSelected;
$this.toggleClass(selClass);
if(willBeSelected) {
$inp.removeAttr('disabled');
} else {
$inp.attr('disabled', 'disabled');
}
});
});
</script>
Read the submitted data in PHP (assuming you're submitting via a POST form):
$selectedImages = $_POST['avatar_image'];
Add a ID to each image, when its clicked grab the id and then inject it into a hidden textfield
<input type="hidden" name="avatar" id="avatar" value="" />
$(".avatar_image").click(function() {
$(this).toggleClass("red");
//assign its id to the hidden field value
$("input[name='avatar']").attr('value', $(this).attr('id'));
// pass that to your DB
});
I presume your using ajax to grab this data back
success : function(callback){
$("image[id*='"+callback.avatar+"']").addClass('red');
}
Try this
PHP: Add the id for the friend to the html you had
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend' data-id='$thisFriendsId>
</div>
JS: Create an empty array. Use each function to go through push the selected id into your array. Then use post to submit to your php.
selected = [];
$(function(){
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
$('.submit').click(function(){
$('.red').each(function(){
var selectedId = $(this).data('id');
selected.push(selectedId);
});
$.post ('http://mysite.com/process.php', selected, function() { alert('succes!'); });
});
​});​

Categories

Resources