How to make jquery reference dynamic html elements - javascript

Below is part of a script I have which dynamically adds html input text boxes. Each one of these input boxes should be an autofil text box. This is the code I'm using - http://www.nodstrum.com/2007/09/19/autocompleter/. Demo is here - http://res.nodstrum.com/autoComplete/.
For the above example it is only one input box but my code allows for dynamic input text boxes (i.e. the user clicks on a button and more pop up).
The problem I have is I don't know how to fix the jquery so that it's dynamic for the input text box id. How do I make it dynamic so that fill() outputs data to foo01, foo11, foo21 etc. not just foo11?
<script src="jquery-1.2.1.pack.js" type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+""}, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#foo11').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
<script type="text/javascript">
var x = 1;
function add() {
var fooId = "foo";
for (i=1; i<=2; i++)) {
var element = document.createElement("input");
element.setAttribute("type", fooId+x+i);
element.setAttribute("name", fooId+x+i);
element.setAttribute("id", fooId+x+i);
if(i==1){
element.setAttribute("onkeyup", "lookup(this.value);");
element.setAttribute("onblur","fill();");
element.setAttribute("value", "First name");
}
if(i==2){
element.setAttribute("value", "Last name");
}
var foo = document.getElementById("fooBar");
foo.appendChild(element);
}
x++;
}
</script>
rpc.php
<?php
include_once("includes/config.php");
$conn = new mysqli("$localhost", "$dbusername", "$dbpass", "$db", "3306"))
if(!$conn) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $conn->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
// Run the query: We use LIKE '$queryString%'
// The percentage sign is a wild-card, in my example of countries it works like this...
// $queryString = 'Uni';
// Returned data = 'United States, United Kindom';
$query = $conn->query("SELECT name FROM cities WHERE name LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo '<li onClick="fill(\''.$result->name.'\');">'.$result->name.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
****************EDIT*****************
It needs to be filled individually. It looks like this:
Text Box (foo00) Text Box
Add
If you click on Add you get
Text Box (foo00) Text Box
Text Box (foo10) Text Box
Add
If I was to click on text box (0,0) and started typing "Lo" a text box would pop up with London, Logon etc. Then if you click on "London", only (0,0) will be updated and will now be "London" i.e.
London Text Box
Text Box Text Box
Add
Now I click on the text box below London (foo10) and start typing "Ro" and a text box would pop up with Rome, Romania etc. I click on Rome and only foo10 should be updated and will look like this:
London Text Box
Rome Text Box
Add
Hopefully that helps with the questions below.
I've never used jquery before this example. I'm using jQuery 1.2.1 because that's what the example said. I'll need to look into a newer version of JQuery.
************** EDIT 2 **********************
I didn't realise that the file rpc.php called fill(), which is where I believe the issue to be. I've updated the code above to include rpc.php and the jquery which calls it.

In the following function, you have hard coded the id foo11
function fill(thisValue) {
$('#foo11').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
Instead, you can use this operator to access the specific textbox that called the fill() method.
function fill(this) {
$(this).val(thisValue); // will access the current element but not sure where you are getting the value
setTimeout("$('#suggestions').hide();", 200);
}
and change the onblur like this
element.setAttribute("onblur","fill(this);");
After reading your updated question, I tried to make a sample application but unfortunately I can't make it to work without changing too much. The problem is, the method you are using to create auto complete works in a way that it is difficult to make it work with dynamically added HTML. So here are my 2 alternatives.
Make some changes in the rpc.php code and only emit values as array and create HTML on the client.
Since you are already using jQuery, try jQuery autocomplete
You can find info about autocomplete here and here
I already made a sample for you using jQuery autocomplete. Check this fiddle

Related

Prevent paragraph from adding new line (JAVASCRIPT, HTML)

I have a program I'm writing that will display countries and sub-county via an array of information. I've decided to include a part where instead of displaying in a text area, I just want it to display via paragraph output.
However, if the user clicks the button again, it will keep copying and pasting the output. I want to prevent this in case the user does this action
[Current Result after button is pressed multiple times ][1] https://i.stack.imgur.com/enZVW.png
It displays the result multiple times if the button is clicked again.
[How I want it to look like after pressing the button multiple times][2] https://i.stack.imgur.com/dXqYE.png
HTML
<input type="input" id="city"><br><br>
<button id="button2"> <!-- Giving button an ID to be called out in our init function and add an eventlistener -->
Show country/subcountry</button><br><br><br>
<!-- <textarea readonly id="countryOut" style="overflow-y:scroll;
resize: none; margin-left: 2.7em; " ></textarea><br><br> -->
<p id = "countryOut"></p><br><br>
JAVASCRIPT
// display += `${sub}, ${co}\n \n`; // display subcountry, and country with new lines included for spacing
p2.innerHTML += `${sub}, ${co}\n \n`;
}
}
}
function init() {
var button = document.getElementById("button1"); // When country is entered, cities will display
button.addEventListener("click", getCountrySub); // when click event/action is performed, the function of getCountry will execute
var button2 = document.getElementById("button2"); // when city is entered, the region, country, sub country, etc. will display
button2.addEventListener("click", getCities); // when click event/action is performed, the function of getCities will execute
}```
+= sign is making duplicated texts.
Fix this to = will work what you intended.
// AS-IS
p2.innerHTML += `${sub}, ${co}`
// TO-BE
p2.innerHTML = `${sub}, ${co}`
Feels like the code is incomplete, assuming that this is a loop that iterates through both lists
p2.innerHTML += `${sub}, ${co}`
Then I think you are missing a cleanup before you start the output, so before the loops start try this:
p2.innerHTML = ""; // trick is here, when button is clicked clear old results, then show new information
for (const co of countries) { // Please fix to your variable names
for (const sub of co.sub) {
p2.innerHTML += `${sub}, ${co}`;
}
}

Append div only if it does not contain text JQuery

I am creating a social media website and am trying to make a comment textarea appear when users click on a status.
Here is what I have so far:
$(".status").click(function (){
//Check if status div they clicked on contains a textarea already
if($(this).closest('div').innerHTML.indexOf("<textarea name='status_body'>") == -1) {
//Append with textarea
var textarea = "<textarea name='status_body'></textarea>";
$(this).closest('div').append(textarea);
}
});
This was working before I put the if statement in. Of course without the if statement a textarea will be added everytime the user clicks. I would only like for a textarea to appear if there is not one aready.
Another method I tried and failed with is:
if(!$(this).closest('div:contains("<textarea")').length > 0)
You're close, just check for the existence with .length
if ($(this).closest("div").find("textarea").length > 0) {
//contains a text area!
} else {
//Doesnt!
}
Do not search for it as text. You should threat the textarea for what it is, a DOM element.
if($(this).closest('div').find("textarea[name='status_body']").length == 0) {
/*...*/
}

JavaScript to clear SharePoint Text Filter box on focus

I am using the following code to clear default value which is "Keyword ...." from a SharePoint text filter box. I put in an alert at line 10 but it doesn't pop-up. Do you any reason why it would not clear the Text Box when a user clicks inside the box to type something.
<script type="text/javascript">
// Clears text box on click or focus
var TextBoxID = document.getElementById("ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0874742c6012_SPTextSlicerValueTextControl");
TextBoxID.focus(function()
{
if(this.value == "Keyword ....")
{
alert('test line 10');
$(this).val("");
}
});
</script>
It looks like you may have an error in your jQuery selector.
Should that have been $('#'+searchID).focus(...)?
If not, I was mislead by the reuse of "searchID" as a local variable and the name of a class on an element.
Try something like this?
HTML
Search Box: <input onclick="clearPlaceholder();" id="ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0874742c6012_SPTextSlicerValueTextControl" type="text" name="fname" value="Keyword..."><br>
JS
function clearPlaceholder(){
var TextBoxID = document.getElementById("ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0874742c6012_SPTextSlicerValueTextControl");
TextBoxID.value = "";
}
http://jsfiddle.net/z5h6H/2/
Here is the code that solved the issue. I needed to clear the value in the text field when user click inside the text box.
<script type="text/javascript">
// Clears text box on click or focus
var TextBoxID = document.getElementById('ctl00_m_g_22e9e7dd_3da6_4f0b_bc1c_0815182c6012_SPTextSlicerValueTextControl');
TextBoxID.onfocus = function(){
if(this.value == 'Keyword ....')
{
TextBoxID.value="";
}
};
</script>

What is wrong there? textarea shows nothing but value is

I wring a code to show hint to user in textarea in grey color;
Idea is next:
1) Initially in area is "Please, type your enquiry there" in grey color;
2) if user click on it, color change to black and text to ''. This part works fine
3) if user type, but than delete (i.e. left field blank) than we need to put "Please, type your enquiry there" in grey color; And this do not work non in Chrome, non in Firefox.It display nothing. When I use chrome inspector, it shows
element.style { color: rgb(141, 141, 141); }
what is right and "Please, type your enquiry there" in HTML what is also right, but field is empty. What might be the problem???
I specially put console.log and they also display output that should be...
This is HTML:
<textarea name='contact_text' id='contact_text'
onclick='text_area_text_cl();' onBlur='text_area_text_fill();'>
</textarea>
<script>
var contact_text_changed = false;
var contact_contacts_changed = false;
function text_area_text()
{
if (contact_text_changed == false)
{
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your enquiry there');
}
else
{
$("#contact_text").css("color","#000000");
}
// Write your code here
};
function text_area_text_cl()
{
if (contact_text_changed == false)
{
$("#contact_text").text('');
$("#contact_text").css("color","#000000");
console.log('sdfdfs111');
contact_text_changed = true;
}
};
function text_area_text_fill()
{
if ($("#contact_text").val() == '')
{
contact_text_changed = false;
$("#contact_text").css("color","#8d8d8d");
$("#contact_text").html('Please, type your enquiry there');
//document.getElementById('contact_text').innerHTML = 'Please, type your enquiry there'
console.log('sdfdfs');
}
else
{
console.log('__');
}
};
// call funcitons to fill
text_area_text();
</script>
To set the value of a <textarea> you need to use .val():
$("#contact_text").val('');
or
$("#contact_text").val('Please, type your enquiry there');
etc. It's tricky to make "placeholder" code work properly. Newer browsers allow:
<textarea placeholder='Please, type your enquiry there' id='whatever'></textarea>
and they manage it all for you.
edit — from the comments, here's an explanation as to why it appears that .html() works (well, it does work, but read on) initially. The markup contents of a <textarea> element — that is, the DOM structure contained within the element — represents the initial value of the <textarea>. Before any user interaction (and/or before the "value" property of the DOM has been touched by JavaScript), that's what's shown as the value of the field. Changing that part of the DOM, then, changes that initial value. Once there's been some user interaction, however, the initial value is no longer relevant to the page view, so it's not shown. Only the updated value is shown.

Dynamically added input box problem?

I have dynamically added div.In which i have text box.While adding dynamic div i can put a value to the current div but not the previously open divs. I want to ask how to add Value to the previously open text boxes of Div.
Thank You
here is a solution that refresh ALL. (I don't understand the "previously open text box" part of your question. Well I understand it, but it doesn't show in your code. I assume the "rhythm" column of your table is an input/textarea html element (since you use it's value).
Please note I'm not sure what the vitalset function is supposed to accomplish, or what "vitals_form_readings_1_rhythm" is.
function queryDb(statement)
{
dbQuery = new air.SQLStatement();
dbQuery.sqlConnection = db;
dbQuery.text = statement //"SELECT * FROM rhythm";
//alert(dbQuery.text);
try {
dbQuery.execute();
} catch (error) {
air.trace("Error retrieving notes from DB:", error);
air.trace(error.message);
return;
}
return (dbQuery.getResult());
}
function crhythm()
{
var statement = "SELECT * FROM rhythm";
return queryDb(statement)
}
function reading_speedcode()
{
if (!cvitals) {
var crhythms = crhythm();
var i=0;
$(crhythms).each( function () {
crhythm = this.crhythm;
var pr = 'card_' + i;
$('#rhythm1').append('<br/><td class="content_big" id="'+pr+'" name="'+pr+'">' + crhythm + ' </td>');
i++
});
}
});
$(document).ready( function () {
reading_speedcode();
$('#rhythm1 .content_big').live('click', function(event) {
$('#rhythm1').empty()
reading_speedcode();
});
});
now, there are several things about your code.
variable naming. (for god sake use meaningful names!)
reading full table when you need one row
where is cvitals declared or assigned?
string parsing. Jquery is good at working with set of elements, there should be no need to parse "pr" to recover the row number.
if a value is inserted in rhythm table (or deleted) before your click, the vitalset logic fails. you might want to use the table id instead.
make sure "#vitals_form_readings_1_rhythm" is unique, not retrieved from the table.
if you can answer my question from the top of this post(vitalset function, vitals_form_readings_1_rhythm, cvitals) I will try improve the code.

Categories