I have a a page that contains search toolkit. So when the search button is clicked, results will be fetched by a ajax from database and appended to a div.
It also shows number of records retrieved from database! I want to be able to do something immediately after the counter shows up a value.
I tried on click of the search button, but it only shows from the second click onward. Because when first clicked the search button, the data were not even fetched from database. Also, after data loaded, when click again it actually shows number of previously fetched records.
I thought, jquery's load() would suit better, but it doesn't too. Below are my attempts that failed. Can anyone suggest the best method please?
//This shows number of items fetched from database
len=data.length;
$(".len").append("<span class='light_blue' id='found'>"+len+"</span>
<span class='rm2' id='tname'> Tutors found</span>");
//This is how the results (fetched data) are appended into a div to be shown in the search page!
$(".the-inner-return").append("
All I want to do is to alert the count (basically I want to replace the text for id='tname' with something else when the count is 0 and 1 and more then 1).
Failed attempts:
$("#search").on("click",function()
{
alert($("#found").text());//alerts the count
});
$(".the-inner-return").on("load",function()
{
alert($("#found").text());//alerts the count
});
$(document).on("click", "#search",function(){
alert($("#found").text());//alerts the count
});
$(document).on( "load", ".the-inner-return", function() {
alert($("#found").text()); //alerts the count
});
You can trigger an alert each time the innerHTML for .len gets changed, for instance like this you get an alert whenever len>0:
$('.len').bind("DOMSubtreeModified", function () {
if (len > 0) {
alert('changed');
}
});
len = 5;
$('.len').bind("DOMSubtreeModified", function() {
if (len > 0) {
alert('>0');
}
});
$(".len").append("<span class='light_blue' id='found'>" + len + "</span><span class='rm2' id='tname'> Tutors found</span>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="len"></div>
Related
I have a list of 2 columns, the first one is "City" which is choice type.the second column is "Other" which is a single line of text.
when the user chooses "other " in City I want "OtherCity "column appears, if he chooses another choice, I want to hide.
I write the code using simple javascript, I do not want to use any library just simple code in javascript.
<script type="text/javascript">
function mySelectfunction(){
getValue = document.getElementById("City").value;
if(getValue == "other"){
document.getElementById("OtherCity").style.display ="none";
}else{
document.getElementById("OtherCity").style.display ="block";
}
}
</script>
but it does not work. can you help make it work?
*another question: if the second column which I want to hide type is "lookup " will the code be different?
My test code for your reference,and Choice and lookup column do not need to change the code.
Add a script editor in NewForm,and insert the code into it(replace the column name).
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script>
<script src="https://xxxx.sharepoint.com/sites/dev/SiteAssets/sputility.js">
</script>
<script>
$(document).ready(function () {
// Get a single select dropdown field
var relacionField = SPUtility.GetSPField('CityLookUp');
// create a function to show or hide Rates based on Rate value
var showOrHideField = function() {
var relacionFieldValue = relacionField.GetValue();
// Hide the Rates field if the selected value is Especial
if(relacionFieldValue === 'other') {
SPUtility.ShowSPField('Other')
}
else {
SPUtility.HideSPField('Other')
}
};
// run at startup (for edit form)
showOrHideField();
// make sure if the user changes the value we handle it
$(relacionField.Dropdown).on('change', showOrHideField);
});
</script>
You can download sputility.js here: https://archive.codeplex.com/?p=sputility
Updated:
Did the code above report any error?
JavaScript code:
ExecuteOrDelayUntilScriptLoaded(show,"sp.js");
function show () {
//Get the select element corresponding to column
var selectElement=document.getElementById('CityLookUp').parentNode.parentNode.childNodes[3].childNodes[3].childNodes[0];//chnage coulmn name
//get tr the hidden column located
var trElement=document.getElementById('Other').parentNode.parentNode;//change column name
//hide tr when we get into page,if the default value is 'other' ,do not need this
trElement.style.display='none';
//select change event
selectElement.onchange = function () {
var index = selectElement.selectedIndex;
//get option value
var value = selectElement.options[index].text;
if(value==='other'){
//show tr element
trElement.style.display='';
}else{
//hide tr element
trElement.style.display='none';
}
}
}
The code idea is to find the corresponding select element and decide whether to hide the tr element where column other is located according to the value of option.
Tip: Our page dom structure may be different, so you may need to modify the code according to your page dom structure. You could view your page dom structure by Developer tool.
Test result:
I have a website where real estate properties search results are displayed like using <div>s with just 6 displayed by default and "load more" button. When user clicks Load more button, 9 more posts displayed, etc. How it is done: divs are hidden by default (display: none;) and then .show class is added to the next 9 items.
a("span.more-search-items").on("click", function(t) {
t.preventDefault();
var e = a(this).parents(".property-search");
e.find(".prop").not(".show").slice(0, 9).each(function() {
var t = a(this).attr("data-img");
a(this).css("background-image", "url(" + t + ")"), a(this).find(".main-image").attr("src", t), a(this).addClass("show")
}), 0 == e.find(".prop").not(".show").length && a("span.more-search-items").hide();
e.find(".prop.show").length
When user goes to single property and then hits back browser button, it shows the first 6 items again. I tried to implement history.pushState() method there where URL changes for each "load more" button click:
var href = window.location.href.replace(window.location.hash, '');
var currentPage = location.hash.replace("#","");
history.pushState(null, null, href + "#" + (+currentPage + 1));
URL changes but the story is still the same - only first 6 results are being displayed when user goes back in history. Is there something I can do in this situation?
If you need to deal with History API you need
on load more click you need to push or replace the history with something like the numbers of visible divs with hash #15 , #24 something like this
With push/replace state you need to use $(window).on('popstate' , function(){ alert(window.location.hash); }) and while user goes to single property it refresh all the page and when browser back button clicked it returns and refreshes the previous page .. so you need to check alert(window.location.hash); when page load
Finally when you got an alert with the number from window.location.hash you can then show the divs depending on it
Ok let me explain this for you in code
$(document).ready(function(){
alert(window.location.hash); // check the alert here
$('.load_more_button').on('click' , function(){
if(window.location.hash){
var href = window.location.href.split('#');
var currentPage = parseInt(window.location.hash);
history.pushState(null, null, href[0] + "#" + (+currentPage + 1));
}
});
$(window).on('popstate' , function(){
alert(window.location.hash); // check the alert here
});
});
You can start from here when you get the number do as you like
I have a button on one page another button on a different page. This second button has the text in it "0 items selected". When the first button is clicked I want to increase the number in the second button by one.
Seeing it is transferring data over different pages I didn't manage to do it the standard way.
Please do not suggest PHP, I am unable to use it.
var yetVisited = localStorage[0];
if ($('.#CallToActionCustomise').click()){
localStorage++;
}
$('.#CallToActionCustomise').click(function(){
$(".Main_MenuButtonReview").append(localStorage);
});
<button class="Main_MenuButtonReview">0 items selected <i class="fa fa-caret-down"></i></button>
You need to access localStorage as if it were an Object, not an array.
Also, you can only store String values, so to get a number to perform math on, you will need to use parseInt.
localStorage.setItem('yetVisited', 0);
$(".Main_MenuButtonReview").text(localStorage.yetVisited + ' items selected');
$('.CallToActionCustomise').click(function()){
localStorage.yetVisited = parseInt(localStorage.yetVisited) + 1;
$(".Main_MenuButtonReview").text(localStorage.yetVisited + ' items selected');
}
Here's an example.
In addition to the above answer, I think you need to init some tag when it loaded.
Put this code on another page.
$(document).ready(function() {
if (typeof localStorage.yetVisited === 'undefined') {
localStorage.setItem('yetVisited', 0);
}
yetVisited = localStorage.yetVisited;
$('.Main_MenuButtonReview').text(yetVisited + ' items selected');
});
$(document).ready(function() {
// this area means after your page(document) ready completely.
});
I have a webpage I'm building where I need to be able to select 1-9 members via a dropdown, which then provides that many input fields to enter their name. Each name field has a "suggestion" div below it where an ajax-fed member list is populated. Each item in that list has an "onclick='setMember(a, b, c)'" field associated with it. Once the input field loses focus we then validate (using ajax) that the input username returns exactly 1 database entry and set the field to that entry's text and an associated hidden memberId field to that one entry's id.
The problem is: when I click on the member name in the suggestion box the lose focus triggers and it attempts to validate a name which has multiple matches, thereby clearing it out. I do want it to clear on invalid, but I don't want it to clear before the onclick of the suggestion box name.
Example:
In the example above Paul Smith would populate fine if there was only one name in the suggestion list when it lost focus, but if I tried clicking on Raphael's name in the suggestion area (that is: clicking the grey div) it would wipe out the input field first.
Here is the javascript, trimmed for brevity:
function memberList() {
var count = document.getElementById('numMembers').value;
var current = document.getElementById('listMembers').childNodes.length;
if(count >= current) {
for(var i=current; i<=count; i++) {
var memberForm = document.createElement('div');
memberForm.setAttribute('id', 'member'+i);
var memberInput = document.createElement('input');
memberInput.setAttribute('name', 'memberName'+i);
memberInput.setAttribute('id', 'memberName'+i);
memberInput.setAttribute('type', 'text');
memberInput.setAttribute('class', 'ajax-member-load');
memberInput.setAttribute('value', '');
memberForm.appendChild(memberInput);
// two other fields (the ones next to the member name) removed for brevity
document.getElementById('listMembers').appendChild(memberForm);
}
}
else if(count < current) {
for(var i=(current-1); i>count; i--) {
document.getElementById('listMembers').removeChild(document.getElementById('listMembers').lastChild);
}
}
jQuery('.ajax-member-load').each(function() {
var num = this.id.replace( /^\D+/g, '');
// Update suggestion list on key release
jQuery(this).keyup(function(event) {
update(num);
});
// Check for only one suggestion and either populate it or clear it
jQuery(this).focusout(function(event) {
var number = this.id.replace( /^\D+/g, '');
memberCheck(number);
jQuery('#member'+number+'suggestions').html("");
});
});
}
// Looks up suggestions according to the partially input member name
function update(memberNumber) {
// AJAX code here, removed for brevity
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
document.getElementById('member'+memberNumber+'suggestions').innerHTML = self.xmlHttpReq.responseText;
}
}
}
// Looks up the member by name, via ajax
// if exactly 1 match, it fills in the name and id
// otherwise the name comes back blank and the id is 0
function memberCheck(number) {
// AJAX code here, removed for brevity
if (self.xmlHttpReq.readyState == 4) {
var jsonResponse = JSON.parse(self.xmlHttpReq.responseText);
jQuery("#member"+number+"id").val(jsonResponse.id);
jQuery('#memberName'+number).val(jsonResponse.name);
}
}
}
function setMember(memberId, name, listNumber) {
jQuery("#memberName"+listNumber).val(name);
jQuery("#member"+listNumber+"id").val(memberId);
jQuery("#member"+listNumber+"suggestions").html("");
}
// Generate members form
memberList();
The suggestion divs (which are now being deleted before their onclicks and trigger) simply look like this:
<div onclick='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
<div onclick='setMember(450, "Chris Raptson", 2)'>Chris Raptson</div>
Does anyone have any clue how I can solve this priority problem? I'm sure I can't be the first one with this issue, but I can't figure out what to search for to find similar questions.
Thank you!
If you use mousedown instead of click on the suggestions binding, it will occur before the blur of the input. JSFiddle.
<input type="text" />
Click
$('input').on('blur', function(e) {
console.log(e);
});
$('a').on('mousedown', function(e) {
console.log(e);
});
Or more specifically to your case:
<div onmousedown='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
using onmousedown instead of onclick will call focusout event but in onmousedown event handler you can use event.preventDefault() to avoid loosing focus. This will be useful for password fields where you dont want to loose focus on input field on click of Eye icon to show/hide password
So I have something which allows the user to add tabs and take away tabs... however how would I go about generating the default number of tabs based on data from my sql database. For example if they were 4 rows with the same id in the id filed, it would generate 4 tabs as there is 4 rows with the same id.
here is the tab thing I found.
<script>
$(function() {
var total_tabs = 0;
// initialize first tab
total_tabs++;
addtab(total_tabs);
$("#addtab, #litab").click(function() {
total_tabs++;
$("#tabcontent p").hide();
addtab(total_tabs);
return false;
});
function addtab(count) {
var closetab = '×';
$("#tabul").append('<li id="t'+count+'" class="ntabs">Session '+count+' '+closetab+'</li>');
$("#tabcontent").append('<p id="c'+count+'">Tab Content '+count+'</p>');
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#t"+count).bind("click", function() {
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+count).fadeIn('slow');
});
$("#close"+count).bind("click", function() {
// activate the previous tab
$("#tabul li").removeClass("ctab");
$("#tabcontent p").hide();
$(this).parent().prev().addClass("ctab");
$("#c"+count).prev().fadeIn('slow');
$(this).parent().remove();
$("#c"+count).remove();
return false;
});
}
});
</script>
<ul id="tabul">
<li id="litab" class="ntabs add">Add tab + </li>
</ul>
Thanks James
Please refer to this answer, Basically, you have to follow the same principle.
Then, call addtab(rowId) in a for loop by using the returned data from your database.
Still not sure what you meant by rows with the same ID, though.