Changing value of a text box is not working - javascript

My HTML(simplified):
<input class="text" type="text" id="emailbox" value="None">
Note: content1 is the ID of a div that contains the email retrieved from a file using PHP and this part works (it returns the email)
My Javascript:
var email = $.trim(document.getElementById('content1').textContent);
if (!email == "") { document.getElementById("emailbox").value = email; }
The value of the input box is not changing at all
The error is with the line
document.getElementById("emailbox").value = email;
or with the html
ALL CODE: https://pastebin.com/5JSLzHdw

I grabbed your Pastebin code, and if I set the content of your content1 div to be this:
<div id="content1" style="display: none;">EXAMPLE#EXAMPLE.COM</div>
then the following code works as a replacement for the script starting at line 327. This is completely unstyled and I haven't changed any of the code except the essential to make it work.
<script>
$(document).ready(function(){
var email = document.getElementById('content1').textContent;
var register = document.getElementById("para7");
var login = document.getElementById("para8");
var logout = document.getElementById("para9");
if (email !== "") {
register.style.display = "none";
login.style.display = "none";
// It's an input so you need to set VALUE, not innerHTML
document.getElementById('mailbox').value = email;
console.log("We are here")
} else {
window.location.href = "../login/";
logout.style.display = "none";
}
document.getElementById("logo").addEventListener("click",function(){
document.getElementById("homebutton").click();
});
document.getElementById("account").addEventListener("click",function(){
if(!email == ""){
document.getElementById("accountbutton").click();
}
});
})
</script>
Others correctly commented that you shouldn't run your code until the document is ready, hence wrapping it inside that jQuery ready handler.
As you are using jQuery, I would suggest replacing all of your document.getElementById("whatever") instances with the jQuery method $("#whatever") as it will make the code more concise.

If I try your code like this, then document.getElementById('content1') returns null
Did you wrap your code in
window.onload = function() {
// run your script in here
}
or for jQuery
$(document).ready(function() {
...
}
Otherwise your code may try to access the DOM while it isn't ready yet.
See here https://stackoverflow.com/a/13921149/11472484 and here Running jQuery code before the DOM is ready?

Related

Get value from jQuery editor to PHP

I'm using this jquery plugin to create a wysiwyg text editor,
I created a textarea in PHP where:
<textarea name="body" id="body"><?php echo $body?></textarea>
and
<script type="text/javascript">
$(document).ready( function() {
$("#body").Editor();
});
</script>
Now i need to get value of this area for send it to SQL
if (isset($_POST['add-article'])) {
unset($_POST['add-article']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['username'] = htmlentities($_SESSION['username']);
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
// I need this line
$_POST['body'] = htmlentities($_POST['body']);
When I put text into this editor, it doesn't enter (value) into the textarea.
I have to have value before I press the add-article button, beacuse now it gives me an empty text.
I found something like this
function displayText(){
alert($("#body").Editor("getText"));
}
This causes it to return text ( i think only display by JS ) but i completely dont know how to use in my PHP scripts.
Second thing is when i write article and make a mistake something like ( Article title already exist ) ( in one session ) text in textarea stayed, but now doesn`t work it.
I think about if there is an error for example "Title already exist" follows:
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$category_id = $_POST['category_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
In my honest opinion i need something like:
add-article.addEventListener('click', function {
$body (from PHP) = alert($("#body").Editor("getText"))(from JS);
}
Thank you in advance for help.
On the plugin page you referenced, I see this is one of the recommendations. Capture the value you want when the click button is pressed, before the form submits.
Add a script to your form submit to put the texteditor content into this element
<form onsubmit='return getItReady()'>
Add an element to the form you'll use as a proxy element and keep it hidden, something like
<textarea id='txtEditorContent' name='txtEditorContent' style='visibility:hidden;height:0px' tabindex="-1"></textarea>
Then add the script to prepare it
<script>
function getItReady() {
console.log('The content:', $('#body').Editor("getText"));
$('#txtEditorContent').val($('#body').Editor("getText"));
return true;
}
</script>
Then in your PHP, it will come through as $_POST['txtEditorContent'].

Clear the cache for a jQuery variable

I am working on sharepoint edit form, and we can define a function named PreSaveItem(), which will get executed before the form is submitted to the server, as follow:-
<script language="javascript" type="text/javascript">
function PreSaveItem(){
var result = true;
var status=$("select[id*='Status_'] option:selected").text();
if (status == "Closed") {
var analysis = $('input[id^="Analysis_"]').val().trim();
alert(analysis);
alert(Date.now());
if (analysis == "") {
alert("Please Enter Analysis before closing the item");
result = false;
}
}
return result;
}
</script>
The above script will show and alert() if the users change the status to "Closed", while they left an Input field named "Analysis" empty. but seems i am facing a caching issues when the script is reading the updated value for the $('input[id^="Analysis_"]').val().trim();. as follow:-
let say i changed the status to "Closed" + i left the "Analysis" input field empty
click on save
then i will get this alert correctly alert("Please Enter Analysis before closing the item");.
then after getting the alert, i entered some text inside the "Analysis" input field >> click on Save again.
then i will get the same error. and the alert(analysis); will still show the old empty value, while the alert(Date.now()); will show updated date-time.. so seems the var status=$("select[id*='Status_'] option:selected").text(); is being cached?
also the weird thing is that the $("select[id*='Status_'] option:selected").text() is not being cached ...
Clear value after alerting.
<script language="javascript" type="text/javascript">
function PreSaveItem(){
var result = true;
var status=$("select[id*='Status_'] option:selected").text();
if (status == "Closed") {
var analysis = $('input[id^="Analysis_"]').val().trim();
alert(analysis);
alert(Date.now());
if (analysis == "") {
alert("Please Enter Analysis before closing the item");
result = false;
var analysis = undefined;
}
}
return result;
}
</script>
Though clearly not getting what you are trying to achieve but would suggest you to update the method for selected text. It might work
suppose your select options are as follows
<select id="CountryName">
<option>India</option>
<option>Australia</option>
<option>England</option>
</select>
To get the selected text you can directly achieve selected text by:
var getSelected = $('#CountryName').find(":selected").text();

How can I use jquery events to pass variables to php?

I have a form with a drop-down to select a time for scheduling
I didn't use a selector input, instead I used the following html to make the menu for styling reasons.
<div class="tabs">
<div class="apt-time">
<h3>#Time</h3>
<ul class="time-list">
<li class="available">8:00am</li>
<li class="available">9:00am</li>
<li class="available">10:00am</li>
<li class="available">11:00am</li>
<li class="available">12:00am</li>
<li class="available">1:00pm</li>
<li class="available">2:00pm</li>
<li class="available">3:00pm</li>
<li class="available">4:00pm</li>
<li class="available">5:00pm</li>
</ul>
</div>
</div>
Because of this I can't use the POST method to get the data the user clicked on in the menu. So I tried to come up with a solution that could pass a string variable with events to my php page with the GET method in the code below. The if statements are going to be used so the client can't submit the form without clicking on an option in the menu. Is there a way around this without using a selector input?
$('.available').click(function() {
return clockTime = $(event.target).text()
})
$('.btn').click(function() {
if ($('.available').click) {
window.location.href = "textsms.php?"+clockTime
} else {
// warn client that they need to chose a time
}
})
Added AJAX functionality below. The script passes POST values to PHP script named textsms.php without refreshing browser.
Updated Code:
<script>
$('.available').click(function() {
var clockTime = $(this).text();
$.ajax({
url:"textsms.php",
method:"POST",
data:{'clockTime':clockTime,var2:'2',}, // modify fields
success: function(data){
alert(data); // Do something with data received
},
});
});</script>
For testing..
textsms.php:
<?php
print_r( $_POST );
?>
You're not defining the get variable in the redirection:
window.location.href = "textsms.php?"+clockTime
The following will store the "clockTime" in the $_GET['time']
window.location.href = "textsms.php?time="+clockTime
Edit: Anyway your JS is not correct.
var clockTime;
$('.available').click(function(e) {
clockTime = $(this).text();
})
$('.btn').click(function() {
if(typeof clockTime !== "undefined"){
window.location.href = "textsms.php?time="+clockTime
}else{
// warn client that they need to chose a time
}
});
You can use a control variable for this (also defining a css class that show the selected option):
var selectedTime = '';
$('.available').click(function() {
$('.available').removeClass('clicked');
$(this).addClass('clicked');
selectedTime = $(this).text();
})
$('.btn').click(function() {
if (selectedTime != '') {
window.location.href = "textsms.php?time="+selectedTime;
} else {
// warn client that they need to chose a time
}
})
You need to get the value and pass it to your location properly:
$("ul.time-list").on("click","li.available",function(){
var selectedTime = $(this).text();
window.location.href = "textsms.php?varname="+selectedTime;
});
I like using jquery's on event as it allows you to use load content dynamically so long as you target an external static element.
http://api.jquery.com/on/

Error on javascript queryselector

I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.
Here the main javascript
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.
<input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">
I tried 2 functions call.
document.getElementByName("satisfaction_case_number").value = getParameterByName("case")
and
document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")
I have to say I'm kinda blind here. Any flag would be appreciated.
Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.
I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks
Wait till the window has loaded then execute it;
window.onload = function () {
document.getElementsByName("satisfaction_case_number")[0].value = getParameterByName('case');
}
The form is being dynamically generated after the rest of your content has loaded, It's unreliable to rely on timing as connection speeds can vary, using
window.onload will ensure the page is fully loaded before executing.
I tested this by throttling my browser connection to "Slow 3G" and it still worked, Your original piece of code that selected the element by name wasn't selecting the first entry in the NodeList, to do this you need to add [0] before the .value
You can try document.querySelector('input[id *= satisfaction_case_number]').value = 'example'
setTimeout(function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}, 1000);
or try to modify the code that creates HubSpot form:
hbspt.forms.create({
// ...
onFormReady: function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}
});

Get the tag name of a form input value

How does one get the .tagName of a value passed in an HTML form input? This is to check whether the value that has been passed is an 'iFrame'. The input is to only accept iframes
For example:
//HTML
<input type="text" id="iFrame">
<button id="butt">Push</button>
//JavaScript
document.getElementById("butt").onclick = function(){
var iframe = document.getElementById("iFrame").value;
console.log(iframe.tagName);
}
I think you are looking for
var iframe = document.getElementsByTagName("iFrame")
I perhaps did not ask the question in the best way, initially.
I wanted to check if the value passed in the input field was an "iframe" (the input is to only accept iFrames). Since .value returns a string and not an HTML tag, getting the tag name through basic methods would not work. I needed another way.
For anybody else who needs a quick solution, this is how I managed to do it:
document.getElementById("submit").onclick = function(){
var iframe = document.getElementById("iFrame").value;
var check1 = iframe.match(/iframe/g);
var check2 = iframe.match(/frameborder/g);
var check3 = iframe.match(/http:/g);
var check = check1.length + check2.length + check3.length;
if (check === 4) {
alert("good!");
}
}

Categories

Resources