append value to href using jquery - javascript

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

Related

How to get the value from dynamically created checkbox using Jquery with class

I am trying to get the value from checkbox when checked which is created dynamically with jquery associated with html table am using class to get the value but am unable to get it
My code is like this
Input created with Jquery
"<td><div class=" + "checkbox checkbox-primary" + "><input type=" + "checkbox" + " class=" + "cbCheck" + " value=" + "" + data.d[i].Rowname + "" + "" + data.d[i].one + "" + "></div></td>"
Jquery to get the value
$("#table").on(":checked", ".cbCheck", function () {
var id = $(this).attr("value");
alert(id);
});
Please help me how to fix this.
Thanks in advance
Working Fiddle
Try:
$('table tr td').on('click','.cbCheck',function() {
if ($(this).is(':checked')) {
alert($(this).attr('id'))
}
else
alert('unchecked');
});
Use 'change' event:
$("#table").on("change", ".cbCheck", function () {
var id = $(this).attr("value");
alert(id);
});
Instead of creating it like that
use Create element and add id dynamically then use your function I guess it will work, actually worked in my case
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'ptworkinfo';
You can do using following for dynamically created elements:
$(document).on("click", ".cbCheck", function () {
var value=$(this).attr("value");
alert(value);
});

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.

Get values and ids of all span elements inside form

I am trying to get all span elements inside the form. The span elements are turning into input text fields and become editable. When you click away they are turning back into span elements. I will attached fiddle live example.
I gave it a go but the problem is that I am getting both ids but only value of the first span element.
Here is my html:
<span name="inputEditableTest" class="pztest" id="inputEditableTest" data-editable="">First Element</span>
<span name="inputEditableTest2" class="pztest" id="inputEditableTest2" data-editable="">Second Element</span>
<input id="test" type="submit" class="btn btn-primary" value="Submit">
And here is JavaScript with jQuery:
$('body').on('click', '[data-editable]', function () {
var $el = $(this);
var name = $($el).attr('name');
var value = $($el).text();
console.log(name);
var $input = $('<input name="' + name + '" id="' + name + '" value="' + value + '"/>').val($el.text());
$el.replaceWith($input);
var save = function () {
var $p = $('<span data-editable class="pztest" name="' + name + '" id="' + name + '" />').text($input.val());
$input.replaceWith($p);
};
$input.one('blur', save).focus();
});
$("#test").on('click', function(){
var ok = $("span")
.map(function () {
return this.id;
})
.get()
.join();
var ok2 = $("#" + ok).text();
alert(ok);
alert(ok2);
//return [ok, ok2];
});
Here is the fiddle https://jsfiddle.net/v427zbo1/3/
I would like to return the results as an array example:
{element id : element value}
How can I read ids and values only inside specific form so something like:
<form id = "editableForm">
<span id="test1">Need these details</span>
<span id="test2">Need these details</span>
<input type="submit">
</form>
<span id="test3">Don't need details of this span</span>
Lets say I have got more than 1 form on the page and I want JavaScript to detect which form has been submitted and grab values of these span elements inside the form
I will be grateful for any help
$("#test").on('click', function(){
var result = {};
$("span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Here is an example: https://jsfiddle.net/v427zbo1/4/
Container issue:
You should use this selector: #editableForm span if you want to get all the divs inside this container.
$("#editableForm span").each(function (k, v) {
result[v.id] = v.innerHTML;
});
But if you want to get only first-level children elements then you should use this selector: #editableForm > span
Example with getting all the spans inside #editableForm container: https://jsfiddle.net/v427zbo1/9/
If you want to have several forms, then you can do like this:
$('form').on('submit', function(e){
e.preventDefault();
var result = {};
$(this).find('span').each(function (k, v) {
result[v.id] = v.innerHTML;
});
alert(JSON.stringify(result));
//return [ok, ok2];
});
Example with two forms: https://jsfiddle.net/v427zbo1/10/
You can't use .text to return the value of multiple elements. It doesn't matter how many elements are selected, .text will only return the value of the first one.
Virtually all jQuery methods that return a value behave this way.
If you want to get an array of values for an array of matched elements, you need another map. You also need to join the strings with , # as you're producing something along the lines of #id1id2id3 instead of #id1, #id2, #id3:
var ok = $("span").map(function () {
return this.id;
}).join(', #')
var ok2 = $("#" + ok).map(function () {
return $(this).text();
});
That said, you're already selecting the right set of elements in your first map. You pass over each element to get its ID, you already have the element. There is no reason to throw it away and reselect the same thing by its ID.
If I got you right following code will do the job
var ok = $("span")
.map(function () {
return {id: $(this).attr('id') , value: $(this).text()};
}).get();
Check this fiddle.

Javascript append/remove elements

I have one question. Is possible delete <span> element added with javascript append?
When i try remove added span then nothing happens.
Like this:
<script type="text/javascript">
$(document).ready(function(){
$('#SelectBoxData span').click(function(){
var StatusID = this.id;
var StatusIDSplit = StatusID.split("_");
var StatusText = $('#SelectBoxData #' + StatusID).text();
$("#SelectBox").append('<span id=' + StatusID + '>' + StatusText + '</span>');
$("#SelectBoxData #" + StatusID).remove();
InputValue = $("#StatusID").val();
if(InputValue == ""){
$("#StatusID").val(StatusIDSplit[1]);
}
else{
$("#StatusID").val($("#StatusID").val() + ',' + StatusIDSplit[1]);
}
});
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
});
</script>
<div id="SelectBoxBG">
<div id="SelectBox"><div class="SelectBoxBtn"></div></div>
<div id="SelectBoxData">
<span id="StatusData_1">Admin</span>
<span id="StatusData_2">Editor</span>
<span id="StatusData_4">Test 1</span>
<span id="StatusData_6">Test 2</span>
</div>
<input type="hidden" id="StatusID" />
</div>
Please help me.
Thanks.
Yes, you can delete them. However, you can't add click event handlers to them before they exist. This code:
$('#SelectBox span').click(function(){
var StatusID = this.id;
$("#SelectBox #" + StatusID).remove();
});
will only add a click event handler to <span> elements inside of #SelectBox at the time the code is run (so, based on your provided HTML, zero elements). If you want the event handler to react to dynamically added elements then you need to use a technique called event delegation, using the .on() function:
$('#SelectBox').on('click', 'span', function() {
$(this).remove(); // equivalent to the code you had before
});

Javascript to get the div info

I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
​$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});​​​​​​​​
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.

Categories

Resources