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>
Related
I was trying to pass a string to a JavaScript function.
As it's mentioned here - Pass a string parameter in an onclick function
I'm using this simple code-
<!DOCTYPE html>
<html>
<body>
<script>
name = "Mathew";
document.write("<button id='button' type='button' onclick='myfunction(\''" + name + "'\')'>click</button>")
function myfunction(name)
{
alert(name);
}
</script>
</body>
</html>
But in the console it's giving an error like Uncaught SyntaxError: Unexpected token }.
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
Rename your variable name to myname, bacause name is a generic property of window and is not writable in the same window.
And replace
onclick='myfunction(\''" + name + "'\')'
With
onclick='myfunction(myname)'
Working example:
var myname = "Mathew";
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');
function myfunction(name) {
alert(name);
}
The question has been answered, but for your future coding reference you might like to consider this.
In your HTML, add the name as an attribute to the button and remove the onclick reference.
<button id="button" data-name="Mathew" type="button">click</button>
In your JavaScript, grab the button using its ID, assign the function to the button's click event, and use the function to display the button's data-name attribute.
var button = document.getElementById('button');
button.onclick = myfunction;
function myfunction() {
var name = this.getAttribute('data-name');
alert(name);
}
DEMO
document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)
Better to use `` than "". This is a more dynamic answer.
You can pass string parameters to JavaScript functions like below code:
I passed three parameters where the third one is a string parameter.
var btn ="<input type='button' onclick='RoomIsReadyFunc(" + ID + "," + RefId + ",\"" + YourString + "\");' value='Room is Ready' />";
// Your JavaScript function
function RoomIsReadyFunc(ID, RefId, YourString)
{
alert(ID);
alert(RefId);
alert(YourString);
}
Use this:
document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')
Try this ...
onclick="myfunction('name')";
I found this pass id to jquery modal form but seeing as I'm not too jQuery-savvy and I don't know PhP I'm not sure how I would implement this in my example.
My goal is to be able to pass the ID of a button, upon being pressed, to a form. Something like this:
<button id="dynamic_id">
<form id="time_form" action="{% url 'event' pk='button_id' %}" method="post">
# Lots of stuff
</form>
The button_id is where I'd like the button's ID to be.
I thought of something like
function getId(button_id) {
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" %" + "}"';
}
<button id="dynamic_id" onClick="getId(this.id);">
<form id="time_form" action=""> (...)
</form>
But this does not work. I get an error message
400 Bad Request: Your browser semt a request this server cannot understand
UPDATE
I'm not trying this:
function getId(button_id) {
var vk_input = document.CreateElement("input");
vk_input.name = "vk_id";
vk_input.value = button_id;
vk_input.type = "hidden";
document.getElementById("time_form").appendChild(vk_input);
}
But it does not work for some reason. What's wrong with it?
look this:
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
var array_ids = [];
$('.dinamics').each(function(){
//console.log('gdfg');
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>
How aboout this with jquery.
<button id="dynamic_id">
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
$('#time_form').append('<input type="hidden" name="your_button_id" value="'+id+'"/>')
$('#time_form').submit();
})
})
</script>
Button id passed correctly to getId() but generated string does not seems valid, here is some issue with quotes. See reduced example on jsfiddle
try this:
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" ' + "%" + "}";
i recommend you to use jquery, is better an clean.
this is what you want?
<button id="dynamic_id" class="dinamics">Lots of stuff</button>
<button id="dynamic_id_1" class="dinamics">1</button>
<button id="dynamic_id_2" class="dinamics">2</button>
<button id="dynamic_id_3" class="dinamics">3</button>
<button id="dynamic_id_4" class="dinamics">3</button>
<button id="dynamic_id_5" class="dinamics">3</button>
<button id="dynamic_id_6" class="dinamics">3</button>
<button id="dynamic_id_7" class="dinamics">3</button>
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var array_ids = [];
$('.dinamics').each(function(){
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>
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.
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.
I am not sure why this works but not when I pass in numbers
<form id="form1" runat="server">
<div id="facebookPhotos-iFrameContent">
<div>
<p>Log in</p>
<p id="LoginButtonContainer"><input type="image" id="btnLogin" src="images/loginBtn.jpg" /></p>
<p><select id="facebookAlbumDropdown" /></p>
<div id="facebookPhotosContainer" />
</div>
</div>
</form>
AddDropdownItem("-Select something test-", "-1", "testDropdown");
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value=" + sValue + ">" + sText + "</option>");
}
that works
but this does not:
var id = 104388426283811;
AddDropdownItem("-Select something test-", id.toString(), "testDropdown");
What happens is the default option shows up but then when it tries to add the second option it bombs out with no errors that I can see in the firebug console and then in the end the list goes blank (no options) when my code is done running.
JavaScript will interpret integers as strings where needed, there is no need to use toString().
Try putting the value in single quotes, like this:
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value='" + sValue + "'>" + sText + "</option>");
}
You asked, "Why would that matter." The answer. It is a good practice and it prevents problems when your values start having spaces in them. I ALWAYS put attribute values in quotes.
Now, for your problem... I just tried it with the following code and it works like a charm!
<p><select name="MyTestDropdown" id="testDropdown"></select></p>
<script type="text/javascript">
$(document).ready(function () {
AddDropdownItem("-Select something test-", "-1", "testDropdown");
AddDropdownItem("something else", "1", "testDropdown");
AddDropdownItem("another thing", 2, "testDropdown");
var id = 104388426283811;
AddDropdownItem("test big value", id.toString(), "testDropdown");
AddDropdownItem("Profile Pictures", 100001379631246, "testDropdown");
AddDropdownItem("Test Test2", 104388426283811, "testDropdown");
});
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value='" + sValue + "'>" + sText + "</option>");
}
</script>
Your original code actually works, too. I don't think there was a problem with it. :) Maybe you have a problem elsewhere in your code?
Based on the comment thread in the original question, here's my sample page that incorporates your logic (along with wiring up a button to add options to the select):
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$("#btnClick").click(function(e) {
e.preventDefault();
var id = 104388426283811;
AddDropdownItem("-Select something test-", id.toString(), "testDropdown");
//AddDropdownItem("-Select something test-", "-1", "testDropdown");
});
});
function AddDropdownItem(sText, sValue, sDropdownID)
{
$("#" + sDropdownID).append("<option value='" + sValue + "'>" + sText + "</option>");
}
</script>
</head>
<body>
<input id='btnClick' type='submit' value='click'></input>
<p><select name="MyTestDropdown" id="testDropdown"></select></p>
</body>
</html>
I don't have the iframes that you mentioned, but I'm using an input submit element to add items in. I'm preventing the default behavior of a submit button by calling e.preventDefault();, which then prevents the post back. I'm then able to add items to the select element.
I hope this helps.