Javascript, copy text field to new li class - javascript

UPDATED, TO BE MORE CLEAR:
My current field that contains the value ‘1201026404’ (which will change every time) :
<input id="ticket_fields_20323656" name="ticket[fields][20323656]" size="30" style="width:125px;" type="text" value="1201026404" tabindex="11">
The LI where I want the copied value ‘1201026404’ (which will change every time) to go when the page loads:
<ul class="multi_value_field" style="width: 99.5%;">
<li class="choice" choice_id="1201026404">1201026404<a class="close">×</a><input type="hidden" name="ticket[set_tags][]" value="1201026404" style="display: none;"></li>
</ul>
The Javascript that I have already made but need help with:
<script type="text/javascript">
copy = function()
{
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = ‘what goes here??’
n2.value = n1.value;
}
</script>

does this work in firefox:
<script type="text/javascript">
copy = function()
{
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.querySelectorAll("ul.multi_value_field li:first");
n2.innerHTML = n1.value;
}
</script>
this uses querySelectorAll which doesnt exist in IE6,7,8 - otherwise you need to use the id of the element which im not sure you have

You're going to have to use an ID on the li element.
<li id="choice_20323656">
then you can copy it like
<script type="text/javascript">
copy = function()
{
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.getElementById("choice_20323656");
n2.innerHTML = n1.value;
}
</script>
EDIT:
If you can use jQuery 1.6 or up, this will work:
$("#ticket_fields_20323656").keyup(function(e) {
$(".choice")
.attr("choice_id",e.currentTarget.value)
.html(e.currentTarget.value
+ "<a class=\"close\">×</a><input"
+ " type=\"hidden\" name=\"ticket"
+ "[set_tags][]\" value=\""
+ e.currentTarget.value
+ "\" style=\"display: none;\">");
});​
Here's a demo: http://jsfiddle.net/JKirchartz/V2L25/, However you should know, if you have multiple things with the class choice their value's going to change in the same way like this: http://jsfiddle.net/JKirchartz/V2L25/4/

Related

dynamically change value on input (javascript)

The value of my input is supplemented with a variable from javascript.
But this variable is changed, i.e. the dynamic is subtracted or added.
so this value in input is also changed, but only after refreshing the page.
I would like this value in the input to be also dynamically changed, at the same time when I change the value in the variable js.
<input id="kwota2" type="text" name="kwota2" disabled>
<script>
document.getElementById("kwota2").value = localStorage.getItem('sumalist');
</script>
span .deleteitembasket changes the value of the js variable, which I pass to the input.
I've come up with a way to use a function that every time I press deleteitembasket I will overwrite the value in input, but I do not know how to create it, because I am a novice programmer. please help.
$(document).on('click', '.deleteitembasket', function () {
var nazwa = $(this).closest('.produkt').find('.nazwa').text();
var cena = $(this).closest('.produkt').find('.cenaprzedmiotu').text();
var suma = 0;
var id = $(this).closest('.produkt').attr("id");
var li = "<li data="+id+" class='produkt_w_koszyku'><b>" + nazwa + "</b> <span class='cena_w_koszyku'>" + cena + " zł</span><span style='float: right; margin-right: 30px;' class='deleteitembasket'><i class=\"fas fa-times\"></i></span></li>";
var $ul = $(this).parents('ul');
$(this).closest("li").remove();
localStorage.setItem('itemlist', $ul.html());
$("#koszyk .cena_w_koszyku").each(function () {
suma += parseFloat($(this).text());
});
$("#cena span").text(suma.toFixed(2));
localStorage.setItem('sumalist', suma.toFixed(2));
});
You can use the jQuery method .val() to change the input value dynamically,
here is an example:
$('#kwota2').val('Test');
$('.deleteitembasket').click(function() {
$('#kwota2').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="kwota2" type="text" name="kwota2" disabled>
<span class="deleteitembasket">Delete</span>

how to change called class in javascript when button is click?

I have a div which is
<div class="add1"></div>
I want the add1 become add+thenumber of length example:
var n= $('.add1').length + 1;
$('.add1').click(function(){
so what I did is
$('.add+n').click(function(){
but it doesnt work, please help me :(
You can store the number in a data attribute and increment on every click.
Change the class attribute from the data attribute value.
HTML
<div id="myDiv" data-num='1' class="add1">click me</div>
JS
document.getElementById('myDiv').addEventListener('click', function(){
var num = Number(this.getAttribute('data-num'));
num++;
this.setAttribute('data-num', num)
this.setAttribute('class', 'add' + num);
});
Try this
$('.add'+n).click(function(){
});
the n needs to be outside of the quotes else it will interpret it as a string. Like so:
$('.add' + n).click(function(){
At first i read your question wrong and i thought you wanted to change the div's class accordingly. Which you could do like this:
var n = 1;
var n= $('.add'+1).length + 1;
$('.add' + n).click(function(){
$(this).attr('class', 'add' + n); //for if you also want to change the class of the div
});
Make use of .addClass() to add and .removeClass() to remove classes
$('.add1').click(function(){
var n= $('.add1').length + 1; //reads n
$(".add1").addClass("add"+n); //adds new class
$(".add"+n).removeClass("add1"); //removes existing class
});
Here is the example: https://jsfiddle.net/danimvijay/ssfucy6q/
If you want to select the class with combination of a variable, use $('.add'+n) instead of $('.add+n').
$('.add'+n).click(function(){
//place code here
});
Here is the example: http://jsfiddle.net/danimvijay/a0j4Latq/
Here it is!! try this .. I code following exactly you need.
<input type="text" style="display:none;" name="qty" value="0" />
<p id="inc" class="">It's class will be Increased[concate with number]</p>
<input type="button" id="btn" name="btn" value="increase"/>
Now following is Main script that will help you ..
var incrementVar = 0;
$(function() {
$("#btn").click(function() {
var value = parseInt($(":text[name='qty']").val()) + 1;
$(":text[name='qty']").val(value);
$('#inc').removeClass('a' + (value-1));
$('#inc').addClass('a' + value); // I believe class names cannot start with a number
incrementVar = incrementVar + value;
});
});
i posted this code also on www.codedownload.in
Thank You.

append value to href using jquery

I basically have a field element with name="one".As soon as I fill the field,the value should be appended to an href <a name="number" href="example.php" </a> .
It should append it in the format href="example.php?number=one" after i fill the field.Is this possible?Im new to jquery.
I have this for getting the values in the jquery
var num = $("[name='number']").val();
but the rest,appending things,im not sure how to do that.Any help?
Try
var $a = $('a[name="number"]');
//store the original value so that we can handler multiple changes
$a.data('href', $a.attr('href'))
$("#one").change(function () {
$a.attr('href', $a.data('href') + '?number=' + this.value)
});
Demo: Fiddle
Note: This solution does not support handling values from multiple input elements
With this:
var $a = $("a[name=number]"),
href = $a.attr("href");
$a.attr("href", href.split('?')[0] + "?number=" + num);
Cheers
DEMO : http://jsfiddle.net/ETsA8/5/
Html :
<a name="number" href="example.php">ss </a>
<input id="one" type="text" >
Js:
$( document ).ready(function() {
var link = $("[name='number']").attr("href");
$("#one").change(function(){
var a_href = $("#one").val();
$("[name='number']").attr("href", link+'?number='+a_href);
});
});
$('a[name="number"]').attr(href(function(i, oldhref) {
return oldhref + '?number=' + value;
});

How to add and use a Div as a total calculator using Javascript?

I need to make a function which calculates the sum of a users input and compare it to a previously given value, returning the result to the user.
e.g. You previously said you eat 20 meals a week but you have currently listed 5 Dinners, 7 Lunches and 36 Breakfasts. This totals 48 meals.
So far I can read my inputs and add them to a variable as the respondent types it in, showing this in an already existing div. But I need to create a div to show it in for it's actual use. This is where I'm having problems as I can't get this code working.
Note I'm new to JS so some of my code might make no sense. This is everything I've got so far, the bit commented out is what is causing trouble, the rest (assuming I have a div ID'd as 'output') works fine:
<html>
<head>
<script>
var count = 0;
function summer() {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
count = num1+num2+num3;
// if(!document.getElementById("output")) {
// var newDiv = document.createElement('div');
// var divIdName = 'output';
// var myDiv = document.getElementById('buttoner');
// var content = document.createTextNode("")
// newDiv.setAttribute('id',divIdName);
// newDiv.appendChild(content);
// document.body.insertBefore(newDiv, myDiv)
// };
document.getElementById("output").innerHTML = "Your running total = "+count
};
</script>
</head>
<body>
<input type="text" id="number1" onKeyUp="summer()" name="number" />
<input type="text" id="number2" onKeyUp="summer()" name="number" />
<input type="text" id="number3" onKeyUp="summer()" name="number" />
<div id='Buttoner'>
<button type="button" onclick="summer()">Clicking here adds your input to the "count" variable</button>
</div>
<br>
</body>
</html>
Thanks!
edit: thought it might be worth noting that the 'buttoner' div is left over from a previous stage of experimenting and is now used as a placemarker for inserting the new div.
Your problem seems quite simple to me. If that is really all your HTML, your only problem is you don't have the output div.
You can solve this in some ways. Using pure JavaScript...
var output = document.createElement("div"); // Creates a <div> element
output.innerHTML = "Your running total = " + count;
document.body.appendChild(output); // Add the <div> to the end of the <body>
Another way is to put the output div in the HTML, this way you won't even need to change your script:
<div id="output"></div>
If you want the output not to be visible before the input, you can CSS it a little...
<div id="output" style="display: none;"></div>
And make it visible with Javascript whenever you want.
var output = document.getElementById('output');
output.style.display = 'block'; // or 'inline-block', or 'inline', etc. See what fits you better
As you're beginnning with Javascript, I'd recommend you start in the right path by reading on unobstrusive Javascript. I can update the answer with some unobstrusive JS if you want.
UPDATE: If you want to substitute the button div with the new output div, you can simply change the names from output to button / buttoner / whatever you want.
UPDATE 2: Seems like I didn't understand your question correctly. If you want to store the previous answer, you can do it in a variety of ways as well.
One is to store the current answer in a hidden field. For example...
<input type="hidden" id="prevAnswer" value="0" />
Then, in your Javascript, you can do it like this:
var prevAnswer = document.getElementById("prevAnswer")
var prevAnswerValue = parseFloat(prevAnswer.value) || 0;
output.innerHTML = "You previously said you eat " + prevAnswerValue + " meals a week but you have currently listed " + num1 + " Dinners, " + num2 + " Lunches and " + num3 + " Breakfasts. This totals " + count + " meals.";
prevAnswer.value = count;
So you will always have the Previous Answer whenever you calculate a new one.
Try this fiddle:
http://jsfiddle.net/Q65BT/
var pre =0;
var count = 0;
function summer(a) {
var num1 = (parseFloat(document.getElementById("number1").value)) || 0;
var num2 = (parseFloat(document.getElementById("number2").value)) || 0;
var num3 = (parseFloat(document.getElementById("number3").value)) || 0;
if(a==1)
{
pre=count;
count = num1+num2+num3;
document.getElementById("output").innerHTML = "You previously said you eat "+pre+" meals a week but you have currently listed "+num1+" Dinners, "+num2+" Lunches and "+num3+" Breakfasts. This totals "+count+" meals.";
}
}
I'm not sure what behavior you are missing. When I uncomment that block, it seems to work fine. The new DIV is being created on the fly if it didn't already exist.
The code is wordier than necessary, but if as you say, you're a beginner, this is not a bad thing. Here's some possible clean-up:
if (!document.getElementById("output")) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'output');
var myDiv = document.getElementById('buttoner');
document.body.insertBefore(newDiv, myDiv)
};

How to catch creation of DOM elements and manipulate them with jQuery

I'm trying to devise a method of when adding a simple div element with a class and some data-* in it, it will replace it or add into it some other elements. This method should not be called manually, but automatically by some kind of .live() jQuery method, a custom event or some kind like $('body').bind('create.custom'), etc.
I need it this way since I wouldn't know in advance what elements will be created since they will be served through ajax like single empty div's or p's .
<!DOCTYPE html>
<html>
<head>
<title >on create</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" ></script>
<script type="text/javascript" >
jQuery(function($){
$("div.fancyInput").each(function(index,element){
var $div = $(this);
var dataId = $div.attr("data-input-id");
var inputId = '';
var labelId = '';
if(!!dataId){
inputId = 'id="' + dataId + '"';
labelId = 'id="' + dataId + 'Label"';
} // if
var dataValue = $div.attr();
$(
'<p class="fancyInput" >' +
' <label ' + labelId + ' for="' + inputId + '" >A fancy input</label>' +
' <input ' + inputId + ' name="' + inputId + '" value="A fancy input" />' +
'</p>'
).appendTo($div);
}); // .each()
}); // jQuery()
</script>
<script type="text/javascript" >
jQuery(function($){
var counter = 2;
var $form = $('#form');
$('#add').click(function(event){
$('<div class="fancyInput" data-input-id="fancyInput' + counter + '" ></div>').appendTo($form);
counter++;
}); // .click
}); // jQuery()
</script>
</head>
<body>
<a id="add" href="#" > add another one </a>
<form id="form" action="#" >
<p class="normalInput" >
<label id="normalInputLabel" for="normalInput" >A normal input</label>
<input id="normalInput" name="normalInput" value="A normal input" />
</p>
<div class="fancyInput" ></div>
</form>
</body>
</html>
Update:
I checked liveQuery beforehand, it's that kind of functionality that I need, but with the ability to modify DOM elements while the event callback is executed. So it's not just that I need events attached, but the ability to modify the DOM upon element creation. For example: whenever a new is created, it should be filled in (even better if replaced) with the p, label and input tags
You could use a DOM Level 3 Event, like DOMNodeInserted. This could look like:
$(document).bind('DOMNodeInserted', function(event) {
// A new node was inserted into the DOM
// event.target is a reference to the newly inserted node
});
As an alternative, you might checkout the .liveQueryhelp jQuery plugin.
update
In referrence to your comment, have a look at http://www.quirksmode.org/dom/events/index.html, only browser which do not support it are the Internet Explorers of this this world (I guess IE9 does at least).
I can't say much about the performance, but it should perform fairly well.

Categories

Resources