Can't get Javascript to set text - javascript

I see examples for this all over, but for some reason, mine isn't working. I have a textbox that is added dynamically if a certain value is selected in a select list.
The part where the field shows up is working, but I am also trying to add some text to the box, which I can't get to work. I'm also trying to use JS to select the text once it's entered - but haven't gotten that far yet!
Is there something blatantly wrong with this?
function showBox() {
if (document.getElementById("ctl00_Content_WhereFound").value == "Other" || document.getElementById("ctl00_Content_WhereFound").value == "Friend/Employee Referral")
{
document.getElementById('ctl00_Content_WhereDetails').style.display = "inline";
if (document.getElementById("ctl00_Content_WhereFound").value == "Other") {
document.getElementById('ctl00_Content_WhereDetails').innerHTML += 'Enter Other';
} else {
document.getElementById('ctl00_Content_WhereDetails').innerText += "Enter Referral";
}
}
}

First thing I noticed was that you used 'innerHTML' in your if clause and 'innerText' in your else clause. Was that on purpose? They do different things...
It's a pain, but it might be worth using the document.createElement() etc functions to build/modify the dynamic content.
I've had trouble with similar stuff... in general, using the DOM functions rather than innerHTML often fixes it, though it is significantly more verbose. JQuery has some very helpful functions for this.

try this..
function showBox()
{
$Found = document.getElementById("ctl00_Content_WhereFound");
$Where = document.getElementById('ctl00_Content_WhereDetails');
if($Found.value == "Other" || $Found.value == "Friend/Employee Referral")
{
$Where.style.display = "inline";
if($Where.value == "Other")
{
$Where.value = 'Enter Other';
}else
{
$Where.value = "Enter Referral";
}
}
}
You can always assign elements to variables to shorten your code.

This looks like you're attempting to make a change to Asp.Net rendered controls. Make sure you have the actual id of the controls formatted correctly. Typically the UniqueID is formatted like ctl00_Content_WhereFound but the ClientID is formatted ctl00$Content$WhereFound.

innerText isn't supported by at least Firefox. Is there a reason you can't use innerHTML in both cases?
Also, you might want to store the element references to make your code cleaner and faster:
function showBox() {
var eFound = document.getElementById("ctl00_Content_WhereFound");
if (eFound.value == "Other" || eFound.value == "Friend/Employee Referral")
{
var eDetails = document.getElementById('ctl00_Content_WhereDetails');
eDetails.style.display = "inline";
if (eFound.value == "Other") {
eDetails.innerHTML += 'Enter Other';
} else {
eDetails.innerHTML += "Enter Referral";
}
}
}

Related

How do I edit text fields based on checkmarks with JavaScript in Adobe Acrobat?

I am trying to change the text fields in a PDF document in Adobe Acrobat based on which checkmarks are checked. This is what my form looks like below:
I have added the following script to both checkboxes, to be executed on "Mouse Up":
var checkbox1 = event.target.isBoxChecked(0);
var checkbox2 = event.target.isBoxChecked(1);
if (checkbox1 && checkbox2){
this.getField("Text1").value = "1 and 2";
} else if (checkbox1) {
this.getField("Text1").value = "Just 1";
} else if (checkbox2) {
this.getField("Text1").value = "Just 2";
}
I was thinking that this script would record which checkboxes are checked when either of them are clicked and then adjust the text box accordingly, but nothing happens. I do not get any syntax errors when I save the script, either. Any help would be greatly appreciated.
Figured it out. I was able to accomplish what I was looking for by abandoning the "event.target" object and instead directly grabbing the checkboxes by name, just like I did with the text box. This is the code:
if (this.getField("Checkbox1").isBoxChecked(0) && this.getField("Checkbox2").isBoxChecked(0)) {
this.getField("Text1").value = "Both";
} else if (this.getField("Checkbox1").isBoxChecked(0)) {
this.getField("Text1").value = "Just 1";
} else if (this.getField("Checkbox2").isBoxChecked(0)) {
this.getField("Text1").value = "Just 2";
} else {
this.getField("Text1").value = "Neither";
}

JQuery detecting empty p tag

I need to ask for some help with this one so here goes...
I'm creating a WYSIWYG editor using a contenteditable textarea. It automatically creates paragraphs and you can also add in subtitles.
What I would like to be able to do is when the button #addStorySubtitle is clicked, if the currently selected p tag is empty or only contains a zero width space ​, then it will be replaced with the contents of innerDivSubtitle. However, if the p tag has content, use innerDivSubtitle to create a new block level element underneath.
The part I seem to be having trouble with is detecting is the p tag is empty.
Thanks all!
$('#addStorySubtitle').click(function(e){
var innerDivSubtitle = $('<div class="addStorySubtitleWrap" contenteditable="false"><span class="removeStorySubtitle"></span><textarea name="addstorysubtitle" class="addStorySubtitle autoSize" placeholder="Really good subtitle" contenteditable="true"></textarea></div><p>​<p>');
var sel = window.getSelection();
if ($(sel.anchorNode.parentNode) === "") {
alert('empty'); //just for help
$(sel.anchorNode.parentNode).replaceWith(innerDivSubtitle);
} else {
alert('not empty'); //just for help
$(sel.anchorNode.parentNode).after(innerDivSubtitle);
}
});
UPDATE
Thanks for all of your helpful replies!
It turns out that the zero width space detection was causing the issue and I had to use unicode to detect it. Here's what I did to fix it...
var nodCon = $(sel.anchorNode.parentNode).html();
if (nodCon === "" || nodCon === "\u200b"){
alert('empty');
}
I hope this will help you?
if($('p').html() == "" || $('p').html == "​"){
//Do something
}
You can check whether the element has content like this:
checkElementContents(document.getElementById('p1'));
checkElementContents(document.getElementById('p2'));
function checkElementContents(element) {
if (element.innerHTML) {
console.log(element.id + " is not empty");
} else {
console.log(element.id + " is empty");
}
};
<p id="p1"></p>
<p id="p2"> </p>
Be careful with spaces, carriage return etc...
function isEmpty(ele)
{
var count = ele.html().replace(/\s*/, '');
if(count>0)
return false;
return true;
}
console.log(isEmpty($('p')));
Check if empty the following way:
if ($("Your p tag").val().length == 0) { /* Empty */ }

Automatically change a value in a form field

I have a webpage where people enter information (name, job title, address, etc.) and it auto creates a business card for them. I currently have some jQuery that uses .change and looks at a field when a user changes it.
It looks for issues with what they enter, because some things must be in a certain format (ex- They enter the word "Avenue" and it won't let them add the item to their cart until they change it to Ave.)
I am trying to find some way to do this on the fly automatically with JS/jQuery, but I'm not sure what to do. What I would like is for the field to update itself, so if the user puts in "Avenue" it would auto update to "Ave." after the user tabs / exits the field.
Any idea on what JS and/or jQuery can be used to do this?
Here is my current code:
var x = "Clean";
var xD = " ";
$('#cartText4046').change(function () {
if ($(this).val().indexOf("Avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
} else if ($(this).val().indexOf("avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
... Additional rules here, omitted for space.
} else {
x = "Clean";
}
if (x != "Clean") {
$('#cartText4046').addClass("invalid");
xD = x;
} else if (x == "Clean") {
$('#cartText4046').removeClass("invalid");
xD = " ";
}
if (x != "Clean") {
$('.betabutton').html('<span id="addToBaskettext">To add this to the Basket,
please fix the following issue(s):<br><br> ' +xD'</span>');
$('.betabutton').addClass("invalidBtn");
} else if (x == "Clean") {
$('.betabutton').html('<a id="addToBasket" href="#" onclick="actionPageSubmit();return false;"><span id="addToBaskettext">Add to Basket</span></a>');
$('.betabutton').removeClass("invalidBtn");
}
Here is a working sample of what you may be looking for.
$("#textbox").on("change", function() {
$(this).val(function(index, value) {
return value.replace('Avenue', 'Ave.');
});
});
http://jsfiddle.net/decx8sw9/
If you really wanted it to do it after the user has finished making changes ("after the user tabs / exits the field.") you might want to bind to blur (fires when focus is lost/shifted to some other element)...
$('#cartText4046').on( "blur", function() {
$(this).val(function(index, value) {
value = value.replace('Avenue', 'Ave.');
// keep going ... value = value.replace('Street', 'St.') ..
return value;
});
EDIT: I reread the question, and now see that you wanted the correction to happen after the user exits the field. This answer provides inline autocorrection while the user types. I will leave it in case you find it useful after all.
You can lift the code from the jQuery Autocorrect Plugin: jsfiddle.
$("#textbox").autocorrect({
corrections: {
Avenue: "Ave.",
"...": "someWord"
}
});

How to change button text or link text in JavaScript?

I have this HTML button:
<button id="myButton" onClick="lock(); toggleText(this.id);">Lock</button>
And this is my toggleText JavaScript function:
function toggleText(button_id)
{
if (document.getElementById('button_id').text == "Lock")
{
document.getElementById('button_id').text = "Unlock";
}
else
{
document.getElementById('button_id').text = "Lock";
}
}
As far as I know, button text (<button id="myButton">Lock</button>) is just like any link text
(Lock). So the fact that it's a button doesn't matter. However, I can't access the button text and change it.
I tried ('button_id'), (button_id), == "Lock", == 'Lock', but nothing works.
How can I access and change a button text (not value) or a link text?
Change .text to .textContent to get/set the text content.
Or since you're dealing with a single text node, use .firstChild.data in the same manner.
Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.
function toggleText(button_id)
{
var el = document.getElementById(button_id);
if (el.firstChild.data == "Lock")
{
el.firstChild.data = "Unlock";
}
else
{
el.firstChild.data = "Lock";
}
}
Or even more compact like this:
function toggleText(button_id) {
var text = document.getElementById(button_id).firstChild;
text.data = text.data == "Lock" ? "Unlock" : "Lock";
}
document.getElementById(button_id).innerHTML = 'Lock';
You can simply use:
document.getElementById(button_id).innerText = 'Your text here';
If you want to use HTML formatting, use the innerHTML property instead.
Remove Quote. and use innerText instead of text
function toggleText(button_id)
{ //-----\/ 'button_id' - > button_id
if (document.getElementById(button_id).innerText == "Lock")
{
document.getElementById(button_id).innerText = "Unlock";
}
else
{
document.getElementById(button_id).innerText = "Lock";
}
}

onload function revision to check value of a form

I am working on a website and I came across an interesting situation. In this particular website we are using a form that has given fields filled out that can be modified, etc. Part of this form gives the user the option between choosing one language or up to 6 languages. Each of these particular rows of the form are hidden unless the user clicks an add language button. There is also a remove language button. The problem that I am having is that there is an onload function that someone wrote to display the table on the my account page, but it only goes through and omits the sections of the table that are set to display:none; Here is the code for the current onload function:
<script type="text/javascript">
/* call onload with table id(s) */
function TR_set_toggle()
{
/* toggleRow method */
var toggleRow = function()
{
this.style.display = ((this.style.display == '') ? 'none' : '');
return false;
}
for (var oTable, a = 0; a < arguments.length; ++a)
{
oTable = document.getElementById(arguments[a]);
var r = 0, row, rows = oTable.rows;
while (row = rows.item(r++))
row.toggle = toggleRow;
}
}
onload = function()
{
TR_set_toggle('my_table');
}
</script>
It looks a little sloppy to me but maybe that's because I am new to javascript. Anyways, I want to change the function so it loads the table but also goes through each of the items that display none and check to see if they have input or not to display them. I don't understand the syntax of this.style.display = ((this.style.display == '') ? 'none' : ''); 1. How can I add an if statement into this line of code? 2. How can I check to see if a field has input or is set to the default? Any help is appreciated. Thanks.
How can I add an if statement into this line of code?
((this.style.display == '') ? 'none' : '');
is similar to
if( this.style.display == '' ) {
this.style.display == 'none'
}
else {
this.style.display = '';
}
How can I check to see if a field has input or is set to the default?
I dont understand your question. What do you mean with "field"?

Categories