I was wondering what is the proper way of store in html content that is displayed dynamically.
My case is that depending on what is clicked some sort of text is displayed in another part of a website. My first idea was to create a variable in js/jquery script to store this content so the script can access it whenever it is necessary.
this is an example:
var someContent=" Content to be displayed when something is clicked";
var a=$('#myid');
a.click(function(){
$('#myOtherId').text(someContent);
});
But after a while it came to my mind that the content should be stored in the html with a display value set to 'none' and js script should simple toggle its visibility depending wether it has been clicked or not.
Storing the content in js script seems much easier - but something tells me that there is better way to do it...
Indeed, you can do it by having the text in an HTML element, and use either jQuery's .toggle or .show depending on how you want it to respond to a second click:
$("#toggle").click(function () {
$('#msg').toggle(); // or .show() to have it in one way only
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="msg" style="display:none">Content to be displayed when something is clicked</span>
<br>
<button id="toggle">click me</button>
When the content is static, it seems more natural to have it embedded in your HTML, while when the content is dynamic (i.e. it depends on the actual state of the application), you would inject the dynamic part of the text with JavaScript.
For a non-JS-programmer in the development team (but with knowledge of HTML) it would in theory be easier to manipulate the messages when they are embedded in the HTML part of the page.
But this is a matter of opinion really.
Here is a mix of the two:
$("#enter").click(function () {
// Copy the number into the error message
$('#num').text($("#inp").val());
// Show the error message when the number is not even
$('#msg').toggle($('#inp').val() % 2 !== 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter an even number: <input id="inp" type="number" value=1>
<button id="enter">Verify</button>
<div id="msg" style="display:none; color:red">
The number <span id="num"></span> is not even
</div>
Related
I have multiple reason codes (For ex: RC1, RC2...). For each of these reason codes, I want to give the user a text box in which they can enter some comments. Also give them the option of adding multiple text boxes for each reason code.
To allow the user to add a dynamic text box, I have a button which allows the user to do so. If there was only one reason code, I can easily just just append a text box to the pre-existing text box using jquery (Using something like this: JQuery adding class to cloned element).
However since I have multiple reason codes(over 200) it doesnt make sense of having button for each reason code in Jquery. Is there a way for me to search by a basic identifier.
I have pasted the contents of the HTML file generated by my JSP file.
<div id="Reasoncode1">
<div id="inputTextBox_Reasoncode1">
<input type="text" placeholder="Add some text"/><button class="button_Reasoncode1">
+</button>
</div>
</div>
<p>
Reason code2
</p>
<div id="Reasoncode2">
<div id="inputTextBox_Reasoncode2">
<input type="text" placeholder="Add some text"/><button class="button_Reasoncode2">
+</button>
</div>
</div>
My Jquery attempt is:
$(".button_Reasoncode1").click(function() {
$('#Reasoncode1').clone().insertAfter('#inputTextBox_Reasoncode1');
});
$(".button_Reasoncode2").click(function() {
$('#Reasoncode2').clone().insertAfter('#inputTextBox_Reasoncode2');
});
I dont want to do this for each and every reason code, i was wondering if there is a better approach to this.
My JSFiddle: https://jsfiddle.net/mvp71L61/
Assuming all buttons are statically added to the DOM,
$("button[class*='button_Reasoncode']").click(function() {
var rCode = $(this).attr('class').match(/\d+/g)[0];
$("div[id='Reasoncode'+rcode]").clone().insertAfter("input[id='inputTextBox_Reasoncode'+rcode]");
});
I'm actually working with Jquery and at some point I use Jquery selectors to make my page work. The issue here is that the HTML I work with can get very long depending on the data I work with and it looks like this.
HTML
<div class="mailing"></div>
<input type="text" class="mail_subject"/>
<input type="text" class="mail_body"/> <!-- I can have 1 to n number of these -->
<!-- Preview tags -->
<p class='main_subject'></p>
<p class='main_body'></p>
<!--
And a few more things we don't use here
-->
</div>
<div id="table1">
<table id="ranking">
<tbody>
<!-- Data, can have 0 to ~3500 rows -->
</tbody>
</table>
</div>
As you can see, my page is more or less divided in two parts, the <div class="mailing">, which contains a few forms, and the <div id="table1"> that is about displaying lots of data.
In my mailing div I have a few inputs and an auto-updated preview that takes the data from the inputs. What I have here is a kind of "mail builder" with the preview giving me the result with html formatting.
The problem here is about performance, my JQuery is slowed by the table and I got lag when I type in a form and I don't want it to search the whole document as I already know my data will be in the mailing div.
JS
$('.mailing').on('change click keyup keydown', function () {
// Here I append the mail_subject input to the preview
var text = $(this).val();
$('.main_subject').text($('.subject_select').val());
// Here I append each mail_body input to the preview
$('.bodies_select').each(function () {
text = $(this).val();
/*
* Some computation for the text
*/
jQuery('<span/>', {text: text}).appendTo('.main_body');
});
});
I have a few more functions like theses and a few more computation, but I think we got the idea of what my code looks like.
My question is, is there a way, when I use JQuery selectors like $('.main_subject') or $('.bodies_select') to not search the whole DOM document but only in my mailing div for example? The problem is that I can store my elements in variable since it as multiple occasion to be updated.
You can use context with jQuery to improve performances :
$('.bodies_select', '.mailing')
http://api.jquery.com/jquery/#jQuery1
You can even optimize the selectors with some technics :
https://learn.jquery.com/performance/optimize-selectors/
Sure, you just need to place the parent elemenent before
$('.mailing .main_subject')
You should probably read a bit about selectors
https://api.jquery.com/category/selectors/
Let me preface by saying this is all in relation to a Wordpress page. My knowledge of JS is lacking at best and the concept of installing/loading/enqueueing a function on one area of the site and then calling that function in another area of the site is a something that makes sense to me in my head but is very new to me in practice and might need a little explaining.
I have two separate javascript files that I would like to load on a single page, but toggle visibility/display of either based on radio button input. The JS is provided by a 3rd party and is offsite. Their provided code is this:
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
and
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
Each file presents a separate set of filtered results from their database. How can I incorporate both onto a page but only have one or the other showing based on a radio button form input? I would like the page to start off with nothing visible (hopefully giving time for both JS to load in the background while the user selects an option) and then show one or the other depending on what they selected.
You can see a single one of these in action at http://pricelesspetrescue.org/adoptable-dogs/. I'm trying to incorporate the use of an additional file on that same page based on input from the user and only showing one or the other rather than both.
I have tried to manage the following
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript'>
function displayForm(c) {
if (c.value == "2") {
jQuery('#claremontdogContainer').toggle('show');
jQuery('#chdogContainer').hide();
}
if (c.value == "1") {
jQuery('#chdogContainer').toggle('show');
jQuery('#claremontdogContainer').hide();
}
};
</script>
<label>Please select a location to view:</label>
<form>
<input value="1" type="radio" name="formselector" onClick="displayForm(this)"></input>Chino Hills
<input value="2" type="radio" name="formselector" onClick="displayForm(this)"></input>Claremont
</form>
<div style="display:none" id="chdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/FzemP6HU/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
<!-- If I uncomment this second block the whole thing breaks
<div style="display:none" id="claremontdogContainer">
<script src="https://toolkit.rescuegroups.org/j/3/4ANRW3x8/toolkit.js"></script>
<script type="text/javascript">
</script>
</div>
-->
This gets pretty close to what I need. The problem I have is the second script load seems to conflict with the functions they provide in the script. It will display the initial result but does not carry any of the functionality that it should have. http://pricelesspetrescue.org/test-page/ Nothing is clickable inside those results and should be.
Been searching through various similar posts and the wordpress codex and...and...I just haven't been able to come up with anything that seems close enough to what I'm looking for to make the answer click in my head.
Edit: It seems that if I only load one of the scripts in either what I have above or the suggested answer below, all functionality is present when loaded. It's the loading of the second toolkit script that is breaking the page. I'm guessing one would need to be loaded then unloaded before loading the second for it to work. Any ideas?
The toolkit.js file you linked adds some common scripts to the DOM (via document.write function, which is not a good solution - see here: http://www.jameswiseman.com/blog/2011/03/31/jslint-messages-document-write-can-be-a-form-of-eval/), then populates an array (toolkitObjects) with a series of variables that are custom per file and finally loads some other scripts.
It also seems that each file loads a div with a specific class containing all the pets, and each div is identifiable by a specific class ( "rgtk-SOMEID" ) and therefore can be shown/hidden via javascript.
Here is an example of what you can obtain using the div class:
http://jsbin.com/loneyijuye/edit?html,output
I am quite the noob at anything other than some HTML, CSS etc, basic website stuff. My javascript is pretty non-existant too. However we were quoted £2,500 by the people who develop our website to add Paypal on the checkout page! They use a fancy 3rd party program which is a standalone software made by themselves that contains all the products etc. We pay monthly to have access to that and make all website changes (such as price, product name etc) in that.
To cut a long story short, I had a look around and found this:
<script src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
></script>
Now, can I change the data-amount field to pick up what the "value" is on the page in the HTML? That way I can simply just add a button that picks that up. Which would work with paypal.
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input type=hidden name='amount' value='1,038.00'>
Basically, how can I get the javascript code to pick up the value from the HTML (or somewhere else). I only have access to the full HTML of the page.
I am not sure how many of these data fields you have on a page but you could write a JS method to dynamically assign the values of the given HTML.
I would start by giving the HTML you're working with some ID's.
<script id="paypalScript" src="paypal-button.min.js?merchant=YOUR_MERCHANT_ID"
data-button="buynow"
data-name="My product"
data-amount="1.00"
async
onload="assignAmount"
></script>
<div class='basketLabel'>Total Amount To Pay:</div>
<span>£</span>1,038.00</li>
<input id="amount" type=hidden name='amount' value='1,038.00'>
Then write a method to execute onload.
function assignAmount(){
var amtElm = document.getElementById('amount');
var scriptElm = document.getElementById('paypalScript');
scriptElm.dataset.amount = amtElm.value;
}
Then attach the method to the onload event of the script element. Putting the script tag below your data field in the HTML should prevent any load issues you might run into.
I want to search multiple HTML files from a separate page, where I search for text from all the divs which has a specific id for each, whole id containing matched search term will be displayed on the search page in list.
The div list looks like this :
<body>
<div class='vs'>
<div id='header 1'>content 1 here </div>
<div id='header 2'>another text </div>
<div id='header 3'>whatever </div>
</div>
</body>
Please note that I want to perform search from different page and want to display results there with links to the searchable page.
For now I was searching like this :
HTML
<body>
<input type="text" id='search' />
<div class='vs'>
<div id='header 1'>content 1 here </div>
<div id='header 2'>another text </div>
<div id='header 3'>whatever </div>
</div>
</body>
JavaScript
$('#search').on('input', function () {
var text = $(this).val();
$('.vs div').show();
$('.vs div:not(:contains(' + text + '))').hide();
});
It is working on the fiddle here, but I don't want it to work like this, I want to do the search from a separate page remotely and display results there with link to this page.
Solution with jQuery and AJAX:
<form id="searchForm">
<input type="text" id="search"/>
<input type="submit" name="Search!" />
</form>
<div id="resultContainer">
</div>
<script type="text/javascript">
$("#searchForm").submit(function(e) {
e.preventDefault();
var results = $("#resultContainer");
var text = $("#search").val();
results.empty();
$.get("http://example.com/", function(data) {
results.append($(data).find("div:contains(" + text + ")"));
});
});
</script>
Fiddle (This fiddle enables you to search for content on the jsfiddle page, try for example JSFiddle as search term.)
Note however that this does not work cross-domain, because browsers will prevent cross-site scripting. You didn't describe your use-case clear enough for me to know whether you're okay with that.
You'll want to look at using PHP file_get_contents to retrieve the HTML contents of the external page, and from there analyze the data in the <div>s that you are interested in. Ultimately, you'll want to store each individual search term in a JavaScript array (you can create JavaScript arrays dynamically using PHP), and then create search functionality similar to example you posted to search all the elements in your array.
So on page load, you'll want to have a <div> in which you are going to list all the elements from the array. You can list these by looping through the array and displaying each individual element. From there, you will want to call a function every time the user enters or deletes a character in the <input> box. This function will update the <div> with an updated list of elements that match the string in the <input> box.
This is the theory behind what you are trying to accomplish. Hopefully it will give you some direction as to how to write your code.
Update:
If you're looking for a JavaScript only solution, check out a JavaScript equivalent of PHP's file_get_contents: http://phpjs.org/functions/file_get_contents/
From here, you can maybe look at using .split to break up the list. Ultimately, you're still trying to store each individual search term as an element in an array, it's just the method that you retrieve these terms is different (JavaScript as opposed to PHP).
Perhaps I was emphasizing too much on PHP, perhaps it's because it's the web development language I'm most familiar with. Hope this JavaScript-only solution is helpful.