How to name a dynamically created textbox through jquery function? - javascript

I want to give a name to my dynamically created textbox on a specific event.
I have written the following code where the function GenerateTextBox returns the name of the textbox and the value "". The textbox is generated by but the name does not get assigned.
This is to use the name as a reference to the textbox in another php file.
Jquery code for generating textbox:
function GenerateTextbox(value,name1) {
return '<input name = "'+ name1 + '" type="text" value = "' + value + '" /> ';
}
Calling the function:
$("#t11, #t12").click(function(){
var div = $("<div />");
div.html(GenerateTextbox("", c1));
$("#TextBoxContainer").append(div);
});
The php output file is showing the error that c1 is an undefined index...
How do I solve this problem?

Change c1 to "c1". c1 refers to a variable named c1 (which you have not defined) whereas "c1" refers to a String.
div.html(GenerateTextbox("", "c1"));
Working Code:
function GenerateTextbox(value,name1) {
return '<input name = "'+ name1 + '" type="text" value = "' + value + '" />';
}
$("#t11, #t12").click(function(){
var div = $("<div>");
div.html(GenerateTextbox("", "c1"));
$("#TextBoxContainer").append(div);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="t11">Create Textbox</button>
<div id="TextBoxContainer"></div>

Related

Script doesn't work correct

I use this script to show buttons on my page
<script type="text/javascript">
function buttonize(cellvalue, options, rowobject) {
var buttons;
if (rowobject[5] == "False") {
buttons += '<input type="button" value="Edit" onclick="editQuestionnaire(' + options.rowId + ')">';
}
buttons += '<input type="button" value="Delete" onclick="deleteQuestionnaire(' + options.rowId + ')">';
return buttons;
}
</script>
I get buttons that I need, but also I get undefined before buttons.
How to make it does not appear?
You have not initialized your variable with any value here:
var buttons;
so its value is undefined.
Then you are appending string data to it
buttons += '<input type="...
so its current value has to be converted to a string before - and that gets you "undefined".
So just initialize your variable with an empty string at the beginning:
var buttons = "";
Declare buttons with empty string:
var buttons = '';
try to initialize the variable buttons.
var buttons = ''; // since it will contain string..use ''

Calling function from button not working for html created using javascript

I am using javascript to create html page , but not able to call some function on button click .
var alernative = "plot1";
var buttonvalue= "mybutton";
function callme()
{alert("hello");}
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="' + callme() + '";></div>');
In above code , creating a button and giving its value and calling function onclick of button , but when the page loads it shows alert (that should not happen) and it is not alerting on button click .
Hoping for Suggestion or some help .
You need to pass the function name as a part of the string:
$('#' + alernative).html('<div><input style="float:right;" type="button" value="' + buttonvalue+ '" onclick="callme();"></div>');
It is a bad practice to write HTML with strings, DOM exists for one reason!
var input = $('<input/>', {
type: "button",
style: "float: right",
value: buttonValue
}),
element = $('<div/>').append(input);
input.click(function () {
callme();
});
$('#test').html(element);

.val() not getting updated value from input

I have two input fields, and I'm trying to get their values using jquery by clicking a button. It seems like a very simple operation, but for the life of me I can't get it to work. Here is the code snippet:
Name: <input type="text" id="name" value="test1"><br>
Message: <input type="text" id="line" value="test2"><br>
<button id="submitButton">Submit</button>
<script>
name1 = $("#name").val();
line1 = $("#line").val();
$("#submitButton").click(function(){
alert("Name: " + name1 + "\nMessage: " + line1);
});
</script>
If I don't specify the value, the alert returns with undefined for both variables. If I change the values of the input and click the button, it still says test1 and test2. There has to be something simple that I'm missing here, anyone know what it is?
In your code, you fetch the values when the script is initialized, and then reference the value they had at that point in your click function rather than fetching the current value.
Try:
$("#submitButton").click(function(){
name1 = $("#name").val();
line1 = $("#line").val();
alert("Name: " + name1 + "\nMessage: " + line1);
});
name1 = $("#name").val()
creates a new string variable name1 that has the value of $("#name").val() as it is at the moment. .val() does not get called each time you try to access name1. The simplest thing to do would just be to use $("#name").val() instead.
http://jsfiddle.net/wTvku/
As mentioned in other answers, the problem is that you are precomuting the variables and expecting them to magically change. However I would strongly suggest using Vanilla JS
document.getElementById('submitButton').onclick = function() {
var name1 = document.getElementById('name').value,
line1 = document.getElementById('line').value;
alert("Name: " + name1 + "\nMessage: " + line1);
};
you should wrap your code within document.ready() event...
$(document).ready(function() {
name1 = $("#name").val();
line1 = $("#line").val();
$("#submitButton").click(function(){
alert("Name: " + name1 + "\nMessage: " + line1);
});
// Handler for .ready() called.
});
You've set variable values outside of the click function. To the value is set on page load, not whenever you run the function. Try this:
Name: <input type="text" id="name" value="test1"><br>
Message:
Submit
$("#submitButton").click(function(){
name1 = $("#name").val();
line1 = $("#line").val();
alert("Name: " + name1 + "\nMessage: " + line1);
});

Different behavior with .val() and .attr("value") using ajax return data on a clone()'d but uninserted element

As the title says, I'm trying to set the value of a .clone()'d form field using the results of a $.getJSON() request. All of the return values have the same key as the name attribute of the form field they belong to.
Naturally, I tried to use .val("foo") to deal with cross-browser/field type discrepancies but it wouldn't work. Oddly, .attr("value","foo") does.
Any ideas? Is this expected behavior, or an undocumented quirk? Here is the relevant code snippet:
function showSites(){
$.getJSON("process.php?action=showSites", function(data) {
var items = [];
$.each(data.sites, function(key, val) {
var $form = $("#addSiteForm").clone();
var buttons = '<button id="getCert" class="button" href="getCert.php?id=' + val.id + '">Get Cert</button>'
+ '<button id="updateSite" class="button" href="process.php?action=updateSite&id=' + val.id + '">Update Site</button>'
+ '<button id="deleteSite" class="button" href="process.php?action=deleteSite&id=' + val.id + '">Delete Site</button>';
// set siteId
$form.find("input[name=siteId]").attr("value",val.id);
// change values
$.each(val, function(i,v){
$form.find("[name="+i+"]").val(v);
});
items.push('<h3>' + val.name + '</h3>');
items.push("<div class='site'>");
items.push("<form class='siteForm' id='"+val.id+"'>");
items.push($form.html());
items.push("</form>");
items.push(buttons);
items.push("</div>");
});
var foo = items.join('');
$("#sites").prepend(foo).accordion("destroy").accordion();
});
});
You can use .val() property in input tags( text box, textarea,..) only.
attr("attrname","value") this is used to set value to any tags. You can set some dummy attr in div tag and retrieve value attr("attrname");

jquery incrementing number in html name=""

I want the variable inputname to go up by 1 every time a new <input /> is added
e.g.
<input name="1" />
<input name="2" />
<input name="3" />
---html---
<p class="add">Add</p>
<div class="added"></div>
---jQuery/javascript---
$(document).ready(function() {
$("p.add").click(function() {
var inputname = somevar;
var added = "<input type=\"text\" name=\""+inputname+"\" />";
$("div.added").append(added);
});
});
here it is on jsfiddle.net if it helps -> http://jsfiddle.net/gamepreneur/54kzw/
Set inputname like this:
var inputname = $('.added input').length + 1;
This gets the total number of added inputs and increments by one, resulting in the new name.
Change the variable scope
Use this:
// declare your variable here so it exists throughout every call, instead of being
// delcared new with every call.
var inputname = somevar;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type=\"text\" name=\""+(inputname++)+"\" />";
$("div.added").append(added);
});
});
Alternatives:
Grab the number of inputs ($('div.added input').length) and use that for a counter.
Grab the id of the last item $('div.added input:last').prop('name')) and increment it.
You need to declare inputname in the global scope so that it lasts longer than just the duration of the click function and then you need to increment it each time you use it.
I modified your fiddle to this: http://jsfiddle.net/jfriend00/54kzw/2/
var inputname = 1;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type='text' name='" + inputname++ + "' />";
$("div.added").append(added);
});
});
Try
$(document).ready(function() {
$("p.add").click(function() {
var inputname = $('input', $("div.added")).length + 1;
var added = "<input type=\"text\" name=\"" + inputname + "\" />";
$("div.added").append(added);
});
});
Consider adding some other selectors to choose those inputs (like a class selector)

Categories

Resources