I need to create text box using JavaScript. I coded as below:
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
<script>
HTML file:
<input type="text" style="width:200px;" id="no_room" onChange="popuptxt()" required>
<div id="my_div"></div>
It displays number of textbox when I type a number, but I need to clear them when I type another number.
Just reset the content of you block each time :
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
my_div.innerHTML = "";
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
</script>
Just add my_div.innerHTML = ""; before the for loop in popuptxt(). That way it will be cleared each time its called.
Related
I'm newbie in jquery And Data table,
I have problem when to set value for element input from another page using function.
this my 1st page code
{
data: "action_user",
targets: "action_user",
mRender: function (data_app, type_app, row_app) {
if (row_app["id_user"] !== null) {
var va_id_user = row_app["id_user"];
var va_user_name = row_app["user_name"];
var va_gender = row_app["gender"];
var va_address = row_app["address"];
var va_imei = row_app["imei"];
var va_phone = row_app["phone"];
var va_role_name = row_app["role_name"];
var va_email = row_app["email"]; //,supplier_name,supplier_code,address,contact_name,contact_num,status_supp
var va_status_user = row_app["status_user"]; // <a href='#'id='updateDataUser' onclick='javascript:myFunc(" + supplier_id + ")'><i class='fa fa-edit'title='Edit'></i></a>\n\
var data_users = {
id_user: va_id_user,
user_name: va_user_name,
gender: va_gender,
imei: va_imei,
phone:va_phone,
address:va_address,
role_name: va_role_name,
email: va_email,
status_user: va_status_user
};
return"<a id='updateDataUser' href='#' onclick='javascript:editUserFunc(" + JSON.stringify(data_users) + ")'><i class='fa fa-edit activeRecord' rel='13' title='Edit'></i></a>";
// return "<a href='" + data_pict_1 + " 'target='_blank' class='btn btn-info'>" + "<font color='#f2f2f2' size='2em'>" + "Display" + "</font>" + "</a>";
}
}
}
this my html code
<div id="div_add_pic" class="panel panel-default">
<form id="form_add_pic" name="form_add_pic" method="POST" action="">
<div id="form_add_user_response" class="resp"></div>
<div class="box-body">
<div class="form-group">
<label for="username" class="req">User Name :</label>
<input type="text" name="userName" id="userName" placeholder="User Name" class="form-control uppercase" />
</div>
</div>
</form>
</div>
this my function to set input value element .
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
$("#userName").val(userName);}
my function I change to
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
var oForm = document.getElementById("form_add_pic");
var set_userName = oForm.userName;
window.location.href = "index.jsp?url=user_layout& pages=add_user_form"
}
but I've got error
validation.js:1422 Uncaught TypeError: Cannot read property 'userName' of null
at editUserFunc (validation.js:1422)
at HTMLAnchorElement.onclick (index.jsp?url=user_layout&pages=list_users:1)
my console.log printscreen
how to call the element form on another page
I have tried it many times but I've been unsuccessful. Please help!
I think, you have to move all these functions inside
$(document).ready(function(){
//Replace with your code
})
Because your script may be there in top of html tags and while running these scripts, those html inputs are not loaded.
finally I use this code, to get parameter on url address bar
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
I am trying to add and remove dropdown <select>s to a form on a button click. This is the code I have currently. I could have sworn I had this working last night, but when I went to work some more on my project this morning, the dropdowns wouldn't add / remove correctly.
function DropDowns(){
this.counter = 0;
this.addDropdown = function (divname) {
var newDiv = document.createElement('div');
var html = '<select name="cookie' + this.counter + '">', i;
for (i = 0; i < cookies_drop.length; i++) {
html += "<option value='" + cookies_drop[i] + "'>" + cookies_drop[i] + "</option>"
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
this.counter++;
}
this.remDropdown = function() {
$('#dropdowns-container').find('div:last').remove();
this.counter--;
}
}
var dropsTest = new DropDowns();
HTML:
<form action='' method=post id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>
I can only figure out the main problem may be on the server side when you create the cookies_drop variable using json_encode.
Other problems may reside in:
A test on the parameter of addDropdown function is suggested to check if it's valid
In the function remDropdown the decrement of the counter variable must be done only if the element is actually removed
You mixed jQuery and javaScript
Instead of using directly the createElement, making the code more simple and readable, you used the innerHTML property.
So, my snippet is:
// I assume you used something like:
// var cookies_drop = JSON.parse( '<?php echo json_encode($data) ?>' );
var cookies_drop = [{text: "Text1", val: "Value1"},
{text: "Text2", val: "Value2"},
{text: "Text3", val: "Value3"}];
function DropDowns() {
this.counter = 0;
this.addDropdown = function (divname) {
var divEle = document.querySelectorAll('form[id=' + divname + ']');
if (divEle.length != 1) {
return; // error
}
var newDiv = document.createElement('div');
var newSelect = document.createElement('select');
newSelect.name = 'cookie' + this.counter;
newDiv.appendChild(newSelect);
for (var i = 0; i < cookies_drop.length; i++) {
var newOption = document.createElement('option');
newOption.value = cookies_drop[i].val;
newOption.text = cookies_drop[i].text;
newSelect.appendChild(newOption);
}
divEle[0].appendChild(newDiv);
this.counter++;
}
this.remDropdown = function () {
var lastDiv = document.querySelectorAll('#dropdowns-container div:last-child');
if (lastDiv.length == 1) {
lastDiv[0].parentNode.removeChild(lastDiv[0]);
this.counter--;
}
}
}
var dropsTest = new DropDowns();
<form action="" method="post" id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>
I have 2 html textbox for users to enter numbers. To sum those numbers, I am passing the values to JavaScript variable and after addition displaying the result to html div section
<div class="input-left"><span><input class="textbox" id="left" name="count" type="text" size="5" value="" /></span></div>
<div class="input-right"><span><input class="textbox" id="right" name="count" type="text" size="5" value="" /></span></div>
<div id="result"> </div>
javascript:
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
But I have an issue with JavaScript. It not displaying the result. How to add both functions in same onkeyup function.
FIDDLE SETUP
Try this:
window.onload = function(){
var left = document.getElementById('left');
var right = document.getElementById('right');
var result = document.getElementById("result");
left.onkeyup = calc;
right.onkeyup = calc;
function calc() {
var a = parseFloat(left.value) || 0;
var b = parseFloat(right.value) || 0;
result.innerHTML = a + b ;
}
}
JSFiddle: http://fiddle.jshell.net/gYV8Z/3/
Update: To hide the result in case the sum equals zero , change the last line like this:
result.innerHTML = ( a + b ) || "";
JSFiddle: http://fiddle.jshell.net/gYV8Z/4/
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
it your code, var a is local variable. make it global variable.
but i would use this code.
function add(){
return parseFloat(document.getElementById('left').value) + parseFloat(document.getElementById('right').value);
}
document.getElementById('left').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
document.getElementById('right').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
I need to make a box so that when the user enters a value of one through 6, it rolls that many dice. I'm a complete beginner to javascript and any help would be greatly appreciated.
Here's my function:
function NumberValue() {
for (i = 0; i <['randNumber']; i++){
var numberRoll = Math.floor(Math.random() * 6) + 1;
var userNumber = '../images/die' + numberRoll + '.gif';
myNewTag = "<img id='dieImgRandom' src='" + userNumber + "'>"
document.getElementById('dieDivRandom').innerHTML += myNewTag;
And here is my body element:
<h1>Why don't you pick please?</h1>
<div id="dieDivRandom" style="text-align:center">
<p>
<div id="dieImageRand">
<img id="dieImgRandom" alt="die image" src="../images/die1.gif">
<br>
<input type="text" id="randNumber" size=20 value="Enter 1 through 6">
<input type="button" value="Click to Roll" onclick="NumberValue();">
</div>
The function needs to allow a user to submit the number one, two, three, four, five, or six, and that many images need to display on the screen. The images a relocated in my images folder, so relative links will work just fine. That's actually what I need to use. Thank you.
Replace:
for (i = 0; i <['randNumber']; i++){
With:
for (i = 0; i <document.getElementById('randNumber').value; i++) {
The <input /> tag can be accessed by using either of the following:
document.getElementById('inputId').value;
document.formName.inputName.value
Finally, your code becomes:
function NumberValue() {
for (i = 0; i < document.getElementById('inputId').value; i++) {
var numberRoll = Math.floor(Math.random() * 6) + 1;
var userNumber = '../images/die' + numberRoll + '.gif';
myNewTag = "<img id='dieImgRandom' src='" + userNumber + "'>"
document.getElementById('dieDivRandom').innerHTML += myNewTag;
}
}
Use this to read values from textbox
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;
for (i = 0; i <ranNum ; i++){
}
}
EDIT:
If you want to validate the Entered number
add this block of code
function NumberValue() {
var ranNum = document.getElementById('randNumber').value;
if(ranNum < 1 || ranNum > 6) {
alert("Please enter number from 1 to 6 only");
return false;
}
for (i = 0; i <ranNum ; i++){
}
return true;
}
when i have to open this page i want to display all contacts in phone with out click on any button.
Here myFunction() displays all contacts.
I have to call `myFunction()`, in this code. I dont know where to call this function. Help me
var ar1 = new Array;
var ar2 = new Array;
var name, number;
var counter = 1;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
options.multiple = true;
filter = [ "displayName", "phoneNumbers" ];
navigator.contacts.find(filter, onSuccess, onError, options);
}
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
name = contacts[i].displayName;
number = contacts[i].phoneNumbers[j].value;
ar1.push(name);
ar2.push(number);
// here i called myFunction(), but it's displaying one contact in multiple times
}
// here i called myFunction(), but it's displaying one contact in multiple times
}
// Here i called myFunction(), the function is not calling
}
function onError(contactError) {
alert('onError!');
}
// where to call this function
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
</script>
</head>
<body>
</br>
<div id="TextBoxesGroup">
<div id="TextBoxDiv1">
<input type="checkbox" id="checkall" value="check" />selectAll</br> <br />
<br /> <br />
</div>
</div>
</body>
</html>
I cannot catch what you want exactly.
if you want to generating phonenumber checkbox list when your app starts,
just call myFunction() in end of onSuccess() callback.
if you want another time, you should define a event handler that you want like below.
$("#PhonenumberListButton" ).click( function() { myFunction(); } );
and your code can occur index exception during loop.
Let's think about below.
each contact has 1 name but has 1 or more phone numbers
your code pushes each name into ar1 and also pushes each phone numbers of contact into ar2
so ar2.length can be greater than ar1.length
your generating display code use ar2.length for loop. it should make exception if any contact has 2 or more phonenumbers.
This's a reason of stop your loop in onSuccess().
Fixed Code
function onSuccess(contacts) {
for ( var i = 0; i < contacts.length; i++) {
name = contacts[i].displayName;
ar1.push(name);
ar2[i] = []; // array for multiple phone#.
for ( var j = 0; j < contacts[i].phoneNumbers.length; j++) {
number = contacts[i].phoneNumbers[j].value;
ar2[i].push(number);
}
}
myFunction(); // display phone numbers
}
function myFunction() {
$("#checkall").click(function() {
if ($(this).is(':checked')) {
$(":checkbox").attr("checked", true);
} else {
$(":checkbox").attr("checked", false);
}
});
for ( var i = 0; i < ar2.length; i++) {
if ( ar2[i].length ) { // avoid none phone# exception
var newTextBoxDiv = $(document.createElement('div')).attr("id",
'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
'<input type="checkbox" value="'
+ ar1[i] + '"/>'
+ ar1[i] + " " + " " + ar2[i][0] + '</br>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
}
}
}