I'm using ajax to update a textbox once the value in a drop down box has been selected. However, i only update/put text in it if certain conditions are met, so it looks rubbish when there is no message. I was thinking that having a label there would be much better, but is this possible? Can i have an empty label and just update the label text when needed?
Cheers
leddy
Edit:
I'm using php and when the drop down box is selected, I am querying a mysql db (in the reports.php page) - depending on what the result of that is, decides whether i update the textbox or not:
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
document.getElementById('outputText').value = httpObject.responseText;
}
}
function checkException()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
httpObject.open("GET", "reports.php?exceptions="
+document.getElementById('exceptionsID').value+"&date1=" + document.getElementById('date1').value, true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
var httpObject = null;
the textbox is 'outputText' and is set in the setOutput() function
Hope this explains a little better
Cheers
Something like this should change the text of the label.
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
document.getElementById('outputText').innerHTML= httpObject.responseText;
}
}
I updated my original post to reflect the code that was provided. This assumes that you are using the <label>, <div>, or <span> tags
Assuming you're using ASP.NET, yes you can. Using the Text property of the label.
Change the textbox into a span, and keep the id the same. Then change the code to set the innerHTML instead of the value:
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
document.getElementById('outputText').innerHTML= httpObject.responseText;
}
}
The simplest way to handle this without a textbox is to create a SPAN tag, give it an id of "outputText", and then change the innerText of the SPAN like this:
function setOutput() {
if(httpObject.readyState == 4) {
document.getElementById('outputText').innerText = httpObject.responseText;
}
}
Inside your HTML, you'll have your label defined like this:
<span id="outputText">Some default text here</span>
Of course, some CSS styling of the SPAN might be a good thing, but that's another matter for another time. Depending on your layout needs, a DIV tag may be better than a SPAN.
Related
My requirement is : Thers's an input field. When user is going to filled it,
on runtime i searched for #tag and make text bold. And wants to separate both groups of #tags
For Example: "I am more #FromSide #FromSide and would like to speak with someone more #ToSide"
Group1: #FromSide #FromSide
Group2: #ToSide
Here's my code:
`$('#custm-field').keyup(function(){`
`let str = $(this).val();`
`let arr = str.split(" ");`
`$(arr).each((i,e)=>{`
`if(e=="#")`
`{ // $(e).css('font-weight','bold');`
`arr[i].replace(e,"<strong>"+e+"</strong>");}
`let newStr = arr.join(" ");`
`$('#custm-field').val(newStr)`
`});`
This can be achieved using RegEx:
$('#custm-field').keyup(function(){
let str = $(this).val();
str = str.replace(/#(.+?)\s/, '<strong>$1</strong>');
$('#custm-field').val(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="custm-field"></input>
However, the bold effect won't be displayed in input fields, you need a contenteditable element for this.
I've constructed a solution for you,
First of all, you can't add HTML tags inside the value of an input tag. So you have to make use of contenteditable HTML attribute, by setting it to true contenteditable="true" on any element you can start to edit the content of it (write inside it).
NOTE: I added a background-color to make it visible when its empty
<div contentEditable="true" id="text" style="background-color: #eee;"></div>
Your JavaScript (JQuery) would look like this:
Note that your code had many errors I had to fix.
$('#text').keyup(function(){
// get the div element
let e = document.querySelector('#text');
// get only the text inside the element (without the HTML tags)
let str = e.innerText;
e.innerHTML = '';
// create a new element to contain our text because you cant add HTML text inside a DOM element directly
let tag = document.createElement('div');
let arr = str.split(" ");
// this string will contain our HTML and text
let newStr = ``;
$(arr).each((i,e)=>{
if(e[0]=="#")
{
newStr += `<strong>${e}</strong>`;
}
else{
newStr += `${e}`
}
newStr += ` `;
})
// add the string to the inner HTML of the element we created
tag.innerHTML = newStr;
// append the newly created element inside the div
e.append(tag);
// based on Vito Gentile answer
// this is to move the cursor to the end of the text we added, other wise the cursor would be at start of the text
cursorManager.setEndOfContenteditable(e);
});
I made use of the code of this answer, this is where this line cursorManager.setEndOfContenteditable(e); came from. Here is their code for convenience.
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
Hopefully this works like what you want.
I'm developing a quiz that pulls data out of a mysql database, and displays the results as radio buttons. The radio buttons are populated based off of key=>value and generated via a simple forloop. This has been done many times, simple google searching and research will yield all the results needed to accomplish this. The issue that I'm having, or was having (before I decided to just do this with jquery) was when I submit the form it would execute the javascript function to validate whether a button has been selected, but when you select any option other than the first radio button you'd receive the same "make a selection" alert that you would if you had not selected any buttons. Selecting the first radio button would return true and execute the getCheckedValue function call. It seems as though, the script only recognizes that I have one input type and doesn't understand to iterate through the rest of the buttons. I've refactored this function a dozen times, and still have no idea why this doesn't work.
<?php
foreach ($dataReturn as $j => $value){
echo "<input type='radio' class='answer' id='radiobtn' name='radiobtn' value='".$j."'>" .$value." </input><br/>";
}
?>
Above is the loop that generates the radio buttons (just for reference, $dataReturn is the return value of a shuffled associative array. (Which is working as intended)
When the submit button is clicked, it calls the below javascript function.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
return true;
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
}else {
alert("Make a selection.");
}
return false;
}
}
I just can't figure out why this doesn't work. As stated above, using jquery this works perfectly.
Your FOR loop: since JS uses zero-based arrays, you can't have <=, otherwise it will look for an index one higher than what you have. Use < instead;
I moved your validation for whether any fields were checked outside the loop to make management easier. It's cleaner this way than worrying about breakout out of loops in the middle of them.
Here:
function isNull() {
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
}
}
if ( !isChecked ) {
alert("Make a selection.");
return false;
}
}
I don't know how your form tag looks, but here is what you need to prevent the form from submitting if no radio fields are checked:
<form action="" method="post" onSubmit="return isNull();">
Try the code below. You do not want your alert to fire or return false until after the for loop is finished.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
return true;
}
}
alert("Make a selection.");
return false;
}
Also, your php code gives all radio buttons the same id. That is bad; doing so violates w3c standards.
I have two text box which is storing in database using AJAX. But I want to return back the new added row in table structure.
I am using this concept in add product to sell . when I want to add an item then it will be display in a tabular grid format.
This is my AJAX code.
var xmlHttp
function newVendorGridInital()
{
//alert("HI");
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{alert ("Browser does not support HTTP Request"); return }
var item= document.getElementById('itemcode').value;
var url="ajax_NewVendorGrid.php"
url=url+"?itm="+item; // For multiple value send.
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=newVendorGrid
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function newVendorGrid()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("GridRuntimeData").innerHTML=xmlHttp.responseText;
> > > I didn't understand how to target the id field > > > GridRuntimeData
}
}
In my html page I have created a table structure i.e. head part.
In my PHP file I am returning the entire inserted row in a html row format using echo statement.
<?php
echo "<tr><td>".$item."</td></tr>";
?>
and my doubt is how to show that row in table. If I write entire table structure in php code then it will be working fine. But i don't want do all the time to return entire row.
Please Help me.
You can dynamically add rows to a table with Javascript like this:
var table = document.getElementById("mytable");
var td = document.createElement('td');
td.innerHTML = 'new row';
var tr = document.createElement('tr');
tr.appendChild(td);
table.appendChild(tr);
jsFiddle demo here
I have a textbox. What I want is when user enters a word in that textbox, it should call onkeyup function and in the function we should check if spelling is correct or not.
If it is correct we don't do anything if its not we should display an alert message and remove all text from the textbox. Please tell what is the best way to do this?
This is how you would do it
function checkWord()
{
var arr = ....;
var word = document.getElementById('textbox').value;
var found = false;
for (var item in arr)
{
if(item == word)
{
found = true;
}
}
if(!found)
{
document.getElementById('textbox').value = "";
alert("Some message");
}
}
Add checkWord to the onkeyup attribute of you textbox, though I think you'd be better using onchange or onblur.
The arr variable should be written to hold an array of correctly spelt words.
Hope this helps.
I have a HTML table with text in the cells like so:
<tr><td>HELLO</td></tr>
I then have a text area like so:
<input type="text" id="txt_message" name="txt_message"
I want to make it so that when you click inside the table cell, the data (in this case the word 'HELLO') is inserted into the text area (so the user does not have to type it).
I dont know if this is possible, but I am guessing it is and it is 'probably' something in JavaScript.
If anybody has any advice that would be great, Thank you :)
[Working demo]
var textbox = document.getElementById('textbox');
var table = document.getElementById('table');
// add one event handler to the table
table.onclick = function (e) {
// normalize event
e = e || window.event;
// find out which element was clicked
var el = e.target || e.srcElement;
// check if it's a table cell
if (el.nodeName.toUpperCase() == "TD") {
// append it's content to the textbox
textbox.value += (el.textContent || el.innerText);
}
}
Note: all the conditional assignments with || are for cross-browser compatibility.
Here is Working demo using jquery.
To get the value, use innerhtml and a span, more here: http://www.vbforums.com/showthread.php?t=339864
To update the textarea you should be able to do something like: document.getElementById ("text_message").value = x;
a simple jQuery snippet, assuming you have 1 textarea and multiple td's to click over
(function() {
var ta = $('#txt_message');
$('td').bind('click.addtextarea', function() {
var text = $(this).html();
ta.val([ta.val(), text].join(' ')); /* this add words */
/* ta.val(text); this print one word */
});
})()