Not able to populate textarea value if it's updated? - javascript

On click of a button, I am showing a popup with one text area and a submit button.
I am able to enter a value in the textarea (e.g.: "hello1"), and when clicking on the submit button, I am checking the textarea's entered value, it gives me "hello1", and fades out the pop up. (as expected)
Issue: the second time, I click the same button again, I entered the value "hello2", and after submitting, it shows me the last entered value in an alert and fades out.
Below is my code:
function onCalChange(cal) {
// inputField = cal.inputField;
startDate = cal.date;
var calVal = this.id;
popup2(calVal);
}
function popup2(calVal) {
idValue = calVal.split("-");
$('.popup2').css('display','block');
//$('.popup2').addClass('pop_up_bckgd');
$(".popup2").append("<div class='pop_up_bckgd'></div>");
$(".popup2").append("<div class='pop_up_container'><form>\n\
\n\
\n\
<label style='margin-left:65px;margin-top:40px;'class = 'label-value' for = 'reason-for-change-" + idValue[2] + "'>Reason for change</label>\n\
<br>\n\
<textarea id='reasontxt" + idValue[2] + "'style = 'width: 74%;margin-left: 62px;height:100px' class = 'text-box' name = 'reason' required></textarea>\n\
<br>\n\
<div style = 'text-align:center'><input class = 'submit-value2' type = 'button' value = 'Submit' name = 'submit1' onclick= 'clicksubmit(idValue[2]);' '></div ></form>")
}
function clicksubmit(id) {
var idNum= parseInt(id);
if ($('#reasontxt' + idNum).val() == "") {
// alert("1");
$('#reasontxt' + idNum).next(".validation").remove();
$('#reasontxt' + idNum).after("<div class='validation' style='color:red;margin-top:5px'>Please enter Reason for change Field</div>");
} else {
alert('2');
alert($('#reasontxt' + idNum).val());
$('#reason' + (idNum)).val($('#reasontxt' + idNum).val());
// $('#reasontxt' + idNum).val() == ""
$('.popup2').fadeOut();
}
}

After making he change specified by erkaner on the comments, I was able to reproduce the issue by copying your code into this JSFiddle: http://jsfiddle.net/v2djohhw/ (I had to make another minor change to hardcode the value of calVal for testing).
From what I saw, the issue is:
Every time that you click on the button, a form with a textarea and a submit button are appended to the popup (using $(".popup2").append(...));
the id of the textarea depends on the id of the button that was clicked (calVal);
so if the same button is clicked several times [or the button is different but it has an id which third part (as you are splitting it and only using the third value idValue[2]) matches the one of a previously clicked button], you will be appending multiple textarea over time, all of them with the same id.
when you submit, and read the value of the textarea, as there are multiple with the same id, the browser will take the value of the first textarea with the specified id.
Because of that you get always the same value that is the one of the first textarea.
How to fix it? Avoid having multiple elements with the same id.
One possible solution: delete the content of the .popup2 box every time you are going to display it, that way you make sure that the id of the textbox is really unique and you don't face unexpected errors:
$(".popup2").html("");
You can see it working here: http://jsfiddle.net/v2djohhw/1/
If you don't want to (or you cannot) delete the content of the .popup2 box, and want to show all the previous textareas, another solution would be keeping track of the number of times the button was clicked and add that value into the id of the textarea. That way you'll make sure the textbox id will be really unique.
You can see it on this other fiddle: http://jsfiddle.net/v2djohhw/2/

Related

Click all checkboxes on a webpage with HTML script (quickbooks/Safar)

So I created the following script to select all check boxes on a page
(function(d) {
var input = d.querySelectorAll('input[type="checkbox"]');
var i = input.length;
while (i--) {
input[i].checked = true;
}
})(this.document);
It does work to do that, however when trying it in Quickbooks while it does select all the boxes, the website does not register it as actually being selected (the total cost at the bottom remains the same, its like it superficially checks the boxes, visually only with no actual register). Any help would be great.
EDIT: Maybe simulating a click instead of changing the box values?
The only thing that changes when physically selecting a box is the value posted below changes to true from false
You should do :
input[i].setAttribute("checked", "");
The checked attribute is a boolean attribute, so the standard way to add it to an element is to pass an empty string for value.
https://developer.mozilla.org/fr/docs/Web/API/Element/setAttribute#Exemple

use javascript set value to input ,the input value will disappear when it's on focus

i have try to fill some value into input field by javascript(chrome extension)which belong to a form , the value seems not update, and will disappear when i click the other area of the page ,
my code is simple
document.getElementById("editGiftCardNumber").value = "12345";
document.getElementById("editGiftCardNumber").setAttribute('value','12345');
also try to use
setTimeout(function()
e.g. in https://www.elementaryrobotics.com/
, i try to set value in chrome console
input = document.getElementById("comp-jpua0zn5input");
input.value="123";
you will see the 123 is shown in input, if I click other area of the page, the 123 will disappear, how to solve it ?

Add values to text box using buttons - retain and concat original

I've got a text box (called SMS) which is capable of having its value changed by selecting a button (addButton). See the JavaScript
<script>
$(document).ready(function(){
$(document).on('click','.addButton',function(e){
e.preventDefault();
var search_val = $(this).attr('data-value');
$('.sms').val(search_val);
});
});
</script>
I want to be able to add multiple values to this text box without the text boxes value completely updating each time.
For example:
A user can write: hello, your name is (user select 'Name' button and value is inserted'. Your address is (user selects address button).
With my current solution, any button clicked will remove all value form the text box and just insert the value of which ever button was pushed.
Use the function to update it's value:
$('.sms').val(function( index, value ) {
return value + search_val;
});

Homemade "Captcha" System - One minor glitch in javascript, can't enable submit button

So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.

Submitting hidden field data on Android/iOS browsers does not work

I am working on a site which connects to a MySQL database and lets you display/edit the data in it. The site uses JavaScript and PHP, with HTML and CSS parts (these are added using JS).
The site works, does everything I wanted it to do, but only from PC. When I try to use it from a smartphone, some of the hidden fields' value doesn't get submitted correctly to the PHP page responsible to working with them.
First, I have a few of this select box:
var maxLvl;
var select = document.createElement( 'select' );
var trooplist = [archerLvl, giantLvl, wizardLvl, balloonLvl, dragonLvl]; //this array contains numbers, which will be used to set the starting option in the select
select.id = "select" + k + " " + i; //k and i are both variables in their respective for loop: k goes from 0 to 2, in it there's another with i.
select.onblur = function() {
var selectid = this.id;
var last = selectid.slice(-1);
if(last==0){
document.getElementById("hiddenArcherid").value = this.value;
alert(document.getElementById("hiddenArcherid").name + " " + document.getElementById("hiddenArcherid").value);
}else if(last==1){
document.getElementById("hiddenGiant").value = this.value;
alert(document.getElementById("hiddenGiant").name + " " + document.getElementById("hiddenGiant").value);
}else if(last==2){
document.getElementById("hiddenWizard").value = this.value;
alert(document.getElementById("hiddenWizard").name + " " + document.getElementById("hiddenWizard").value);
}else if(last==3){
document.getElementById("hiddenBalloon").value = this.value;
alert(document.getElementById("hiddenBalloon").name + " " + document.getElementById("hiddenBalloon").value);
}else if(last==4){
document.getElementById("hiddenDragon").value = this.value;
alert(document.getElementById("hiddenDragon").name + " " + document.getElementById("hiddenDragon").value);
}
};
select.style.position = "absolute";
select.style.left = 250 + (i*(width + (width/10))) +"px";
select.style.top = 110 + height + (rowcounter * (height * 1.5)) + "px";
select.style.width = width;
if(i==0 || i==1 || i==2 || i==3)
maxLvl = 6;
else
maxLvl=4;
for(var l=0; l <= maxLvl; l++){
var option = document.createElement( 'option' );
option.setAttribute("value", l);
option.innerHTML = "Level " + l;
select.appendChild(option);
}
select.selectedIndex = trooplist[i];
IDarray.push(select.id);
document.body.appendChild(select);
This code runs in a for loop, and creates 5 select boxes using data passed by a function. Then, when the user selects a new option, the option's value is stored in a HTML hidden input field with. Like this one:
var hiddenArcher = document.createElement('input');
hiddenArcher.setAttribute("type","hidden");
hiddenArcher.name = "hiddenArcher";
hiddenArcher.id = "hiddenArcherid";
hiddenArcher.setAttribute("value", document.getElementById("select1 0").value);
formNew.appendChild(hiddenArcher);
These input fields have a basic value, which is the default of the select box - 0 if the user creates a new entry, or an already known value if the user wants to modify an already existing entry. All the input fields have the same structure, only the JS var, the name, the id and the default value changes.
The input fields are part of the formNew form, which has multiple submit buttons - pressing those buttons posts the fields' values to a PHP page, which executes the MySQL queries, depending on which button was pressed. For this, I use if/else if (isset). Then the PHP redirects (by using header("Location: http://my_sites_address"); exit();) to the main page - the one I where the select boxes are.
If I try it from Chrome, the site works - The right values get passed, the PHP executes the right queries correctly. I can add new entry, and both delete or modify existing ones. When I try it on Android (via emulator) or iOS (via my friend's phone), although I can select the values I want to change, and the alerts display the correct data, too, when I hit submit, nothing happens within the database, it seems like I did nothing. The browser gets redirected to the PHP, so I guess the submit does happen, but there will be no changes in the database. The PHP simply redirects to the main page, and that's all.
The only function can be used successfully on phone is deleting the entry, most likely because the hidden field responsible for storing the row's ID gets it's value the moment it's added to (a different) form, and the value never changes, only when the user switches to a different entry.
The hidden fields "physically" (based on their location in the file) are declared later than the select boxes.
Currently, the code acts this way on phone:
1) I start editing the entry. The select boxes show up.
2) I can select the desired value.
3) An alert pops up, confirming the value got passed to the hidden field.
4) I press the submit button, comes the PHP, then the redirects, and I am back where I started. There are no changes in the database.
I already tried to switch onchange to onblur at the select boxes; I made sure JS is enabled (which was totally unnecessary, because the images/texts displayed with JS). Right now I have no idea what's wrong.
Are any of you experienced something similar, or has any idea what should I do?
Some browsers fail to correctly and completely recognize the programmatic change of a hidden input's value immediately after it is changed. If you submit the form directly after changing the hidden input's value via javascript, the value sent for that input will be the pre-change value, rather than the value you set in javascript.
Unfortunately, I don't have a list of browsers that exhibit this behavior, nor do I know the exact mechanics behind it. What I do know is that I've run into the issue you're describing, and I have always been able to solve it by triggering a change event on the hidden input after changing its value via javascript.
For those using plain javascript with no external libraries, your code would look something like this (see here):
<input id="myHidden" name="myHidden" type="hidden" value="old value"/>
<script type="text/javascript">
var hiddenInput = document.getElementById('myHidden');
hiddenInput.value = 'new value';
console.log(hiddenInput.value); // = 'new value'
// Submit the form now, and myHidden='old value' will be sent to the server
// Set up and trigger the change event on our input:
var changeEvent = document.createEvent("UIEvents");
changeEvent.initUIEvent("change", true, true);
hiddenInput.dispatchEvent(changeEvent);
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
For those using jQuery or a similar library, the code is a little more concise:
<input id="myHidden" name="myHidden" value="old value"/>
<script type="text/javascript">
var $hiddenInput = $('#myHidden');
$hiddenInput.val('new value');
console.log($hiddenInput.val()); // = 'new value'
// Submit the form now, and myHidden='old value' will be sent to the server
// Trigger the change event on our input:
$hiddenInput.change();
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
Really concise example (one-liner) using jQuery:
<input id="myHidden" name="myHidden" value="old value"/>
<script type="text/javascript">
$('#myHidden').val('new value').change();
// Submit the form now, and myHidden='new value' will be sent to the server
</script>
Here's a working example using a slightly simplified version of the code supplied in the original question.
In our case, the issue was simply that we had this check in PHP:
if (isset($POST['myvalue']) && !empty($POST['myvalue'])) {
// save
}
However, in PHP 0 is considered empty in PHP and thats exactly what the passed value was!

Categories

Resources