call jquery function from javascript not working - javascript

I read similar posts on this but fails to work at this time. Mine is slightly different.
I call a javascript function addFormField which creates a dynamic input element within a form. This part works fine. Within that function I call the JQuery function loadData(id) to test if the id of the dynamically created element exists but it does not. Is loadData being called correctly to wait $ for the input element id to be created before checking if it's created? Thanks!
function addFormField() {
var id = document.getElementById("id").value;
$("#divTxt").append("<p id='row" + id + "'><label for='txt" + id + "'>Field " + id + " <input type='text' size='20' id='txt" + id + "'><p>");
$(function () {
loadData(id);
});
id = (id - 1) + 2;
document.getElementById("id").value = id;
}
function loadData(id) {
if ( $('#txt' + id).length ){
alert('success');
}
else {
alert ('fail');
}
}
<html>
<p>Add</p>
<form method="get" id="form1" action='#'>
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
</html>

Your code works fine for me: http://jsfiddle.net/6t8eX/
Just make sure that the addFormField() method is global. If it isn't, the inline onClick won't be able to find it.
If it is wrapped in $(function () { }), (or in any other function body) it won't be global.

Related

append() in jquery does'nt append file second time

I have defined an input of type file and a hidden form below it,
<input type="file" name="attachment0" id="attachment0" custom-on-change="uploadfile" ng-show="attachFile" multiple/>
<form class="hidden" id="myForm" method="post" enctype="multipart/form-data" action="SupportRequest">
</form>
"custom-on-change" is an angular directive that calls the function uploadfile() after choosing files. My javascript looks as shown below
var form = $('#myForm');
var n=0;
$scope.attachFile = true;
$scope.uploadfile = function() {
if(n == 0){
var filein = $('#attachment0');
form.append(filein);
$('#attachment0').test();
}
else
{
if(n==1){
var temp = "attachment0" + '_' + n;
var file_in = $('#'+temp);
form.append(file_in);
$('#'+temp).test();}
}
};
$.fn.test = function() {
return this.each(function(){
n++;
$(this).attr('id', this.id + '_' + n);
$(this).attr('name', this.name + '_' + n);
});
};
Am trying to append files twice to the form myForm. When i choose files second time, even after appending, i see that the previously appended input with id="attachment0" is not present in myForm and the input of id="attachment0_1" is present in the form.
Here am trying to upload multiple files multiple times, that is why am dynamically changing the id of the input in test().
I want both input with id attachment0 and attachment0_1 in myForm.
Does anyone know how this can be fixed? And explain this behavior too.
Change your code from form.append(filein) to form.append($('#attachment0').clone()).
It work then. You should use .clone() method to copy elements .
.append() just moves the element from one place to another but for copying first create the copy of the element using .clone() and then append it to your form
looks like in test function you are replacing id,
$(this).attr('id', this.id + '_' + n);
Would is not be better to use ng-repeat? Something like this:
Controller:
$scope.files = [...] // list of files
$scope.uploadfile = function() {
// So stuff to get the file
$scope.files.push(filein);
};
Html:
<!-- Inside the form -->
<div ng-repeat="file in files">{{file}}</div>

Why can't I send the value wit the onchange?

function myFunction(ID) {
var fileSelector = $('<input onchange="javascript:testFunction(' + ID + ',' + this.value +')" type="file" />');
fileSelector.click();
}
my call to the testFunction is with the correct ID, but "Undefined" for this.value
All I want is to pass the value that the input now has WITH the onchange event. Why is it not possible?
Your this keyword inside the myFunction function is the window object. You don't want that.
In fact, you want to use the this.value inside the HTML, so you don't need to interpolate strings.
function myFunction(ID) {
var fileSelector = $('<input onchange="javascript:testFunction(' + ID + ', this.value)" type="file" />');
fileSelector.click();
}
I think what are you trying achieve is simply to remove the codes from the this.value. I did write the correct code below for your requirements:
var fileSelector =
$('<input onchange="javascript:testFunction(' + ID + ', this.value)" type="file" />');

Change form input value with javascript

I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.

How do pass the id of a form onKeyUp?

There's plenty of questions on how to get the value onKeyUp, but I want to pass the id of the form onKeyUp as well.. I tried something like this, but it's telling me getId is not defined.
function getId(x){
$('.not').append(x);
}
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"' onkeyup='getId("+word+")'></form> ");
http://jsfiddle.net/evs3A/
Also is putting something like "+variable+" bad practice, because I'm using it quite a lot ;)? Thank u.
Use jQuery to hook up the event and avoid the problem altogether. Try this:
var word = 'HELP';
$('.why').html("<form class='questions'><input type='text' id='" + word + "'
name='" + word + "'></form> ");
$('.questions input').on('keyup', function(e) {
$('.not').append(this.id);
});
Example fiddle
you can change it into this:
$('.why').html("<form class='questions'><input type='text' id='"+word+"'
name='"+word+"'></form> ");
and in jquery:
$(document).ready(function(){
var word = 'HELP';
$(document).on('keyup', '#' + word, function(){
$('.not').append(word); //or $(this).attr('id'); if the id is the argument that you want to pass
});
});
if you want to change a variable to pass you can use data value like this:
<input type='text' id='"+word+"' name='"+word+"' data-something="new_value">
and take it in this mode:
$(document).on('keyup', '#' + word, function(){
$('.not').append(word);
var value = $(this).data('something');
});
Here's a sample without any jQuery.
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', mInit, false);
function mInit()
{
byId('myFormId').addEventListener('keyup', onFormKeyUp, false);
byId('myFormId2').addEventListener('keyup', onFormKeyUp, false);
}
// this function was attached to the form in the mInit function.
// as a consequence, 'this' reffers to the form itself.
// this.id should give us the id of the form
function onFormKeyUp(e)
{
alert("Keyup detected in the form with the id: '" + this.id + "'");
}
</script>
<style>
</style>
</head>
<body>
<form id='myFormId'>
<input id='textField1'/>
<br>
<button>Some button</button>
</form>
<form id='myFormId2'>
<input id='textField2'/>
<br>
<button>Some button</button>
</form>
</body>
</html>

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

Categories

Resources