Am I using 'this' correctly? jQuery - javascript

I am working on a click event - where it hides any users that are not the same value as the one clicked on. This is a snippet of the relevant HTML.
<div class="main">
<section class="tweets">
<div class="tweet">
<p class="time">Sun Mar 15 2020 20:04:53 GMT-0700 (Pacific Daylight Time)</p>
<p class="users" data="sharksforcheap">#sharksforcheap: </p>
<p class="message">last night i formulated a life #sxsw</p></div>
When I manually input the value of the users value in my :contains it works fine. I'll click on sharksforcheap for example and it will hide every other users that are not of that.
$('.tweets').on('click', '.users', function(){
var user = $(this).data('users');
$('.tweet').not(':contains(sharksforcheap)').hide();
});
However, I want to obviously make it work for any users that I click on as hard-coding it for each user is not feasible. So I made a var called user and referenced it to this which should hold the data of my users. However, this doesn't work.
$('.tweets').on('click', '.users', function(){
var user = $(this).data('users');
$('.tweet').not(':contains('+ user + ')').hide();
});
Am I using this incorrectly in this context?

This is how you need to specify data-users attribute to get its value with .data("users"):
<p class="users" data-users="sharksforcheap">#sharksforcheap: </p>
But it seems that what you need is easier achieved with
$('.tweet').not($(this).closest('.tweet')).hide();

Related

Why do my inputs on the page disappear after refreshing the page, but the inputs are saved in local storage in the console?

link to my web application: https://malekmekdashi.github.io/work_day_scheduler/
link to my github repo: https://github.com/malekmekdashi/work_day_scheduler
I cannot seem to solve this issue that I'm having. My goal is that whenever I refresh the page after inputting some values in the text box, the values will remain on the page along with local storage. However, I am unable to do so. If someone can be so kind as to help me solve this issue, I would greatly appreciate it. Here is a little example of the code that I'm working with
HTML:
<div class="row time-block" id="1">
<div class="col-md-1 hour" id="1">9am</div>
<textarea class="col-md-10 description" id="inputValue"></textarea>
<button class="saveBtn col-md-1"><i class="fa fa-save"></i></button>
</div>
Javascript:
$('.saveBtn').on('click', function() {
var inputValue = $(this).siblings('.description').val();
localStorage.setItem("inputValue", inputValue);
});
$('inputValue .description').val(localStorage.getItem('inputValue'));
Your selector is wrong in two ways.
Like in the comments already said: Your return will be an array. You have multiple ids inputValue with class description.
You want to select id inputValue, which means you need to use #inputValue. Also you need to combine them by leaving out the whitespace otherwise you search for childrens. Correct jQuery would be $('#inputValue.description')

Showing form input data in a different ID in same form

I have a form with input textboxes with IDs as follows:
#ApplicantFirstName
#ApplicantSurname
#ApplicantAddress
#ApplicantPostcode
Later in the form, there is a consent where I need to show the above details in a statement.
I have the consent as follows:
<p>I <span id="ApplicantFullName"></span> of <span id="ApplicantFullAddress"></span> hereby give my permission for the company to share personal information with other service providers</p>
The function is then triggered on a dropdown being clicked with onclick="updateConsent(); being added to the dropdown.
I have written the following but it's not working:
<script type="text/javascript">
function updateConsent(){
document.querySelectorAll("#ApplicantFirstName, #ApplicantSurname").innerHTML = document.getElementById(ApplicantFullName).innerHTML ;
document.querySelectorAll("#ApplicantAddress, #ApplicantPostcode").innerHTML = document.getElementById(ApplicantFullAddress).innerHTML ;
}
</script>
Is that the correct script to use?
I'm not getting any errors, just doesn't appear to be working
You use "#ApplicantFirstName, #ApplicantSurname","#ApplicantAddress, #ApplicantPostcode" but your id in the HTML has the first letter as lower case. Note that Javascript is cAsE sEnSiTivE
Change the Javascript:
function updateConsent(){
document.querySelectorAll("#applicantFirstName, #applicantSurname").innerHTML = document.getElementById(applicantFullName).innerHTML ;
document.querySelectorAll("#applicantAddress, #applicantPostcode").innerHTML = document.getElementById(applicantFullAddress).innerHTML ;
}
OR change the HTML:
<p>I <span id="ApplicantFullName"></span> of <span id="ApplicantFullAddress"></span> hereby give my permission for the company to share personal information with other service providers</p>

Change title of web page according to form elements

I'm looking to change the title of an html page according to certain form elements, as well as some text found on that page. I found a good site describing how using Javascript can do almost what I need, located here: http://www.devx.com/tips/Tip/13469.
The problem with the script found there is that the option to change the title is restricted to the textarea, or if I try to include another element, I get an error message. I authored web page/form templates, nothing complicated, where the intended users, who, shall we say, are not very computer literate(one of them has never used computers), fill out certain textareas and drop-down options and then save the pages in an ARCHIVE folder. To make it easier for them, I would like to give them the luxury of saving the pages without having to type the relevant date and # (each form is basically one of a series of 59), essentially standardizing the titles of the saved pages which should make it easier to categorize them using another script in the future. Can the code below(the one found in the above web site) be extended to include more than one html item, such as the select drop-down options found below, and maybe something found inside elements such as a or div?
<HTML>
<HEAD><TITLE>Change Title Dynamically:</TITLE></HEAD>
<BODY>
<FORM action="" method=POST name="SampleForm">
<B>Enter Title for the window:</B>
<TEXTAREA NAME=WindowTitle ROWS=1 COLS=50></TEXTAREA>
<INPUT TYPE=BUTTON VALUE="Change Title" ONCLICK="javascript:UpdateTitle()">
</FORM>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
function UpdateTitle()
{
document.title = document.SampleForm.WindowTitle.value;
}
</SCRIPT>
</BODY>
</HTML>
<SELECT>
<option>-----</option>
<OPTION>JAN</OPTION>
<OPTION>FEB</OPTION>
<OPTION>MAR</OPTION>
<OPTION>APR</OPTION>
<OPTION>MAY</OPTION>
<OPTION>JUN</OPTION>
<OPTION>JUL</OPTION>
<OPTION>AUG</OPTION>
<OPTION>SEP</OPTION>
<OPTION>OCT</OPTION>
<OPTION>NOV</OPTION>
<OPTION>DEC</OPTION>
</SELECT>
I would recommend jQuery to get the values of the fields you want to display in the title and set it. More info on jQuery can be found at http://jquery.com/
You can use a jQuery selectors to get the values of the fields and concatenate it accordingly. Something like this:
document.title = $('textarea').val() + ' - ' + $('select').val();

Div acting as a form input (onclick)

I have a page which connects to a database where I have some users. Then, it takes each user and puts a div for each one of them, so I have 6 divs (a user in each div).
What I want is that, when somebody clicks in a div, it would give me the id of that user like if it was a form with an input.
I mean: the page takes the id and the name of each user from the database, so if I used a normal input, I would make that when the form is submitted, the form would return me the id of the selected user, but as I am using divs and no buttons, it would be nice to achieve that.
This is how my page looks (number 4 is where my mouse is):
The structure is basically, as I said, 6 divs, each one containing the name and the id of the user (I hide the names for privacy).
So, what can I do? If I haven't explained well I can give you more details... Thanks!!
Your HTML should be generated similar to this (each div has an attribute to point to its corresponding user from the DB)
<form id="select-user" action="formActionPage.php" method="POST">
<input id="selected-user" type="hidden" value="0">
</form>
<div id="1" class="user"></div>
<div id="2" class="user"></div>
<div id="3" class="user"></div>
The form has no submit button as you mentioned but has an input which is hidden notice that value=0 is a default value chosen by me .. you may control this in the action page ..
JQuery:
$("div").on('click', function() {
$('#selected-user').val($(this).attr('id'));
$('#select-user').submit();
});
EDIT
you may use div.[classname] div.user in my example, because you just don't want to apply this for any div
Use this:
HTML code:
<div><span id='userId'>10</span></div>
<div><span id='userId'>11</span></div>
jQuery code:
$("div").on('click', function() {
var userId = $("span", $(this)).text();
console.log(userId);
});
CSS code:
span {
display: none;
}
Main idea is to create in each div hidden span in which you will store user id, connected to this div. Also, you need onclick event, which will find this span and show needed id. Simple. Demo below.
DEMO
Note, that it is just an example. You can edit it as you need

dynamic window.find not working with jQuery

I can't for the life of me figure out why this isn't working.
I want to search the current page for text using a search box. I googled and found this: http://www.javascripter.net/faq/searchin.htm . I implemented the code into my site, but it doesn't work. the function ( findString() ) works, but only when I hard-code a string (as in i can't use javascript or jquery to get the value of a text input). I made this fiddle: http://jsfiddle.net/alyda/CPJrh/4/ to illustrate the problem.
You can uncomment different lines to see what I've tested.
jQuery has a method :contains() that will make easier what you are looking for.
Take a look here: fiddle
$("button[type='submit']").click(function () {
var string = $('#search').val();
var matched = $('li:contains(' + string + ')');
matched.css('color','red');
console.log(matched);
return false;
});
I found a fix (sort of). It seems that the input needs to be placed well AFTER the content to be searched in the DOM. That means I've done the following:
<section class="content">
<h2>Fire</h2>
<h3>Fire Extinguishers</h3>
<ul>
<li>Model 240</li>
<li>Model C352, C352TS</li>
<li>Model C354, C354TS</li>
</ul>
...
<div id="navbar">
<ul>
...
</ul>
<input id="search" type="text" class="form-control pull-left" placeholder="Search for part number">
<button id="submit" type="submit" class="btn btn-default pull-left" style=" margin-top:6px;">Search</button>
</div>
as you can see, I've moved the input (which is in the navbar div) BELOW all of the text I want to search, and used CSS to programmatically place the navbar at the top of the page. I don't particularly like this setup (as it messes with the flow of content) but since I was looking for the quickest and simplest implementation of a single-page search, it will have to do.
I would still love to know why this happens, when the javascript is at the end of the DOM where it belongs...
In firefox I noticed that the fiddle (v4) as given in the question worked, but not in the way the asker expected it to.
What happens in firefox is that the function does find the value..: you have just entered it in the input-field. Then the browser's find method seems to hang in the 'context' of the input 'control' and doesn't break out of it. Since the browser will continue to search from the last active position, if you select anything after the input-field, the function works as expected. So the trick is not to get 'trapped' in the input-field at the start of your search.
A basic (dirty) example on how to break out of it (not necessarily the proper solution nor pure jquery, but might inspire a useful routine, since you now know the root of the problem in FF):
$( "button[type='submit']" ).click(function(){
var tst=$('#search').val(); //close over value
$('#search').val(''); //clear input
if(tst){ //sanity check
this.nextSibling.onclick=function(){findString( tst );}; //example how to proceed
findString( tst ); //find first value
} else { alert('please enter something to search for'); }
return false;
});
Example fiddle is tested (working) in FF.
PS: given your specific example using <li>, I do feel Sergio's answer would be a more appropriate solution, especially since that would never run line: alert ("Opera browsers not supported, sorry..."), but the proper answer to your window.find question is still an interesting one!
PS2: if you essentially are using (or replicating) the browser's search-function, why not educate the user and instruct them to hit Ctrl+F?
Hope this helps!
I had same problem in an angularjs app and I fix it by changing DOM structure.
my HTML code was something like this:
<body>
<div class="content" >
<input class="searchInput" />
<p>
content ....
</p>
</div>
</body>
and I changed it to something like this:
<body>
<div class="search">
<input class="searchInput" />
</div>
<div class="content">
<p>
content ....
</p>
</div>
</body>
Note: I'm aware that this topic is old.

Categories

Resources