I'm kind of new to JQuery.
I've been trying to use this Jquery http://jsfiddle.net/54pp2/2/ ,
<input id="click" type="button" value="click" />
<label id="test">Test</label>
$(document).ready(function () {
var textArray = [];
textArray[0] = 'test 1';
textArray[1] = 'test 2';
textArray[2] = 'test 3';
textArray[3] = 'test 4';
var idx = 0;
$('input#click').on('click', function() {
idx++;
var newidx = idx % textArray.length;
$('label#test').text(textArray[newidx]);
});
});
But when i put it in my theme code, it won't work, even though the jsfiddle shows that it works just fine.
If you want to see: http://dialoguetest.tumblr.com/
(where when you click the pink button on the sidebar, the description text changes. But you can only click it once, unlike the jQuery code that enables the button to be clicked a few times for the text change.)
When i tried to use the jQuery, it won't work: http://dialoguetest2.tumblr.com/
Is there something i'm missing? I know that I have to add
<script type="text/javascript">
and end it with
</script>
in order to make it work. But is there something else i'm missing, like using the Google AJAX Libraries API?
If so, how is it possible?
To make this work in a HTML page you need to place a script reference to jQuery along with your JS code (in a DOM ready handler) in the head. Something like this:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript>
$(document).ready(function () {
var textArray = [];
textArray[0] = 'test 1';
textArray[1] = 'test 2';
textArray[2] = 'test 3';
textArray[3] = 'test 4';
var idx = 0;
$('input#click').on('click', function() {
idx++;
var newidx = idx % textArray.length;
$('label#test').text(textArray[newidx]);
});
});
</script>
</head>
<body>
<input id="click" type="button" value="click" />
<label id="test">Test</label>
</body>
</html>
Related
I made a chrome extension where my popup button calls a script. The other script uses jQuery but I get an error saying jQuery is not defined.
My popup.html:
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
My popup.js:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('record');
login.addEventListener('click', function() {
chrome.tabs.executeScript({file: 'markStudents.js'});
});
});
myScript.js:
var arrays = []
$.get('Attendance.txt', function(data){
var splitted = data.split("\n"); // --> should return an array for each line
// Loop through all lines
for(var i = 0; i < splitted.length; i++)
{
var line = splitted[i];
// Now you could remove [ and ] from string
var removed = line.replace('[','').replace(']','');
var refined = removed.replace(' ', '');
// Now you can split all values by using , delimiter
var values = refined.split(',');
var array = [];
// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++)
{
var value = values[c];
array.push(value);
}
arrays.push(array);
}
});
var present = arrays[0];
console.log(present);
var absent = arrays[1];
console.log(absent);
var user = present[0];
var pass = absent[0];
var loginField = document.getElementById('fieldAccount');
var passwordField = document.getElementById('fieldPassword');
loginField.value = user;
passwordField.value = pass;
var loginForm = document.getElementById('btn-enter-sign-in');
Is there any way to include my jquery.js in myScript.js?
Console Error
Just import jquery before you import popup.js
Like this
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
Inside Your popup.js, when you load markStudents.js which uses jQuery, you'd again have to load jQuery before same
Like this
document.addEventListener('DOMContentLoaded', function () {
var login = document.getElementById('record');
login.addEventListener('click', function () {
chrome.tabs.executeScript(null, { file: "jquery-3.4.1.min.js" }, function () {
chrome.tabs.executeScript(null, { file: "markStudents.js" });
});
});
});
Just reorder your script tags and put jQuery before your popup.js. That way it will be loaded when you try to call it.
yo can use this code to include another jquery file in your jquery:
$.getScript("file address");
like this:
$.getScript("/assets/pages/scripts/ui-blockui.min.js");
I am making a extension theme for my Chromebook that searches coding sites (like this site, w3schools, ect.) How sould I make it? This is my code so far:
<html>
<head>
</head>
<body>
<input id="input1">
<button onclick="searchGoogle()">Search Google</button>
<script>
function searchGoogle() {
var one = document.getElementById("input1").value;
var two = 'http://www.google.com/search?q=' + one;
window.location = two;
}
</script>
</body>
</html>
My code doesn't work
When it runs, this pops up:
(Image of my code running)
Is my code wrong?
Any help will be aapreciated.
EDIT
<html>
<head>
<script src="searchgoogle.js">
</script>
</head>
<body>
<input id="input1">
<button id="link">Search Google</button>
</body>
</html>
and
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
function searchGoogle() {
var one = document.getElementById("input1").value;
var two = 'https://www.google.com/search?q=' + one;
window.location = two;
}
});
});
Didn't work either
You declare the function searchGoogle inside the listener function but it is never called. Try with:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
//there is no need to declare a new function here.
var one = document.getElementById("input1").value;
var two = 'https://www.google.com/search?q=' + encodeURIComponent(one);
window.location = two;
});
});
I have this code and trying to print the results but it's not printing, please help. thankyou.
function GetRandom() {
var myElement = document.getElementById("pwbx")
var myArray = ['item 1', 'item 2'];
var item = myArray[(Math.random()*myArray.length)|0];
myElement.value = (item);
}
<!DOCTYPE html>
<html>
<body>
<p> click the button to run the fumction</p>
<button onclick="GetRandom()">Try it</button>
<p id="pwbx"></p>
</body>
</html>
it works where i use the input form type to get the results but i don't want that, i want it to just be echoed as a normal text in the page. thanks. i am a noob in this stuff so looking for help.
function GetRandom() {
var myElement = document.getElementById("pwbx")
var myArray = ['item 1', 'item 2'];
var item = myArray[(Math.random()*myArray.length)|0];
myElement.value = (item);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random number between 1 and 10.</p>
<button onclick="GetRandom()">Try it</button>
<input name="test" type="text" id="pwbx" value="">
<p id="pwbx"></p>
</body>
</html>
<p> tag doesn't have a value property. Use innerHTML instead.
function GetRandom()
{
var myElement = document.getElementById("pwbx")
var myArray = ['item 1', 'item 2'];
var item = myArray[(Math.random()*myArray.length)|0];
myElement.innerHTML = item;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a random number between 1 and 10.</p>
<button onclick="GetRandom()">Try it</button>
<p id="pwbx"></p>
</body>
</html>
as Tim said in the comments... you will want to use innerHTML not value for non input tags....
<!DOCTYPE html>
<html>
<body>
<p> click the button to run the fumction</p>
<button onclick="GetRandom()">Try it</button>
<p id="pwbx"></p>
</body>
<script>
var myArray = ['item 1', 'item 2']; //should move this outside of getRandom so it doesn't reallocate each run;
function GetRandom() {
var randomInt = Math.floor(Math.random() * Math.floor(myArray.length));
var item = myArray[randomInt];
document.getElementById("pwbx").innerHTML = item;
}
</script>
</html>
I have the following piece of code, which changes one line of text in a click of a button:
<!DOCTYPE html>
<html>
<body>
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'This is JavaScript!'">
Click Me!</button>
</body>
</html>
This is quite easy since there is no script, no function needed to handle the button. Now, I want this same button to change back to the first content when I click it again. I assume that now I need to have a function, but not sure how to write it. An ideas?
You don't have to use a function. You could do it with a ternary operator ? and :, or you could even just write an if else statement all on one line.
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML === 'This is JavaScript!' ? document.getElementById('demo').innerHTML = 'Watch this HTML content changes..' : document.getElementById('demo').innerHTML = 'This is JavaScript!';">
Click Me!</button>
However, that is a lot of code to cram into one line and it would be much cleaner in a separate function, as such.
function changeText() {
var demo = document.getElementById('demo');
if (demo.innerHTML === 'This is JavaScript!') {
demo.innerHTML = 'Watch this HTML content changes..';
} else {
demo.innerHTML = 'This is JavaScript!';
}
}
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Well. Although the way you are trying is not the best practice.... But the following way will give you some hope. try to do more research.
function myFunction() {
var x=document.getElementById("demo").innerHTML;
if(x=="A Paragraph."){
document.getElementById("demo").innerHTML="Back Again";}
if(x=="Back Again")
document.getElementById("demo").innerHTML="A Paragraph.";
}
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
More simply, this function works:
<h1>Change content exercise</h1>
<p id="demo">Watch this HTML content changes..</p>
<button type="button" onclick="changeText()">Click Me!</button>
Javascript:
function changeText() {
e = document.getElementById('demo');
e.innerHTML = e.innerHTML == "Watch this HTML content changes.." ? "This is JavaScript!" : "Watch this HTML content changes..";
}
You can see it working at this JS Fiddle: http://jsfiddle.net/0yLb4a3j/
You can have something like a toggle function:
<script type="text/javascript">
function toggleContent() {
var message1 = "This is JavaScript!";
var message2 = "Watch this HTML content changes..";
var element = document.getElementById('demo');
if (element.innerHTML===message1)
element.innerHTML = message2;
else
element.innerHTML = message1;
return false;
}
</script>
You get it called by setting onclick="toggleContent();" on the button.
You could use an IIFE, an array, an incremented counter, and a modulo operator to achieve this.
document.getElementById('button').onclick = (function(){
var demo = document.getElementById('demo');
var text = [demo.textContent,'This is JavaScript!'];
var count = 0;
return function() {
demo.textContent = text[++count % 2];
}
})();
<p id="demo">Watch this HTML content changes..</p>
<button type="button" id="button">Click Me!</button>
var btn = document.getElementById("<btn_id>");
var previous = "";
btn.addEventListener("click", clickHandler);
function clickHandler() {
var demo = document.getElementById("demo");
if (!previous) {
previous = demo.innerHTML;
} else {
demo.innerHTML = "This is JS";
btn.removeEventListener("click", clickHandler);
}
}
first of all , you ll need to do the code in a seperate script, in brief , append the intial text to the div then wheck button clicked, change it to second text, and according to your question you ll need a second button who will change the div text to the intial text , logically that ll give something like tht :
<script>
window.onload = function(){
document.getElementById('demo').innerHTML = 'Watch this HTML content changes..'
}
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = 'This is JavaScript!'
};
document.getElementById('button1').Onclick = function(){
document.getElementById('demo').innerHTML = ''Watch this HTML content changes..'
};
</script>
Problem : So I have alerted the value of textarea by:
var source = document.getElementById('source').value;
alert(source);
But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried
$("form").submit(function(){
But that also haven't helped me. So how can I do this?
This is my code.
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="http://code.guru99.com/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="http://code.guru99.com/Perl1/codemirror.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
So how can I get the current value of the textarea? Please help me guys.
I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.
When I look at the documentation, I found this:
var source = editor.doc.getValue();
alert(source);
Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:
editor.save();
var source = document.getElementById('source').value;
alert(source);
Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.
Please visit at CodeMirror User Manual for the furher information.
As you have jQuery loaded you can do as follows:
var content = $('#source').val();
alert(content);
Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.
This code will create a button that will alert the content of your textarea when clicked:
<button onclick="alert($('#source').val())">Click me</button>
Try the following inside the submit()
var textAreaVal = $("#print-result").val();
alert(textAreaVal);
Your form does not get submitted when the button in it is pressed since this is not a submit button.
This will not submit the form, and will not alert its' contents.
<input type="button" value="Run" onclick="execute()"/></br>
Add something like this in the form:
<input type="submit" value="Submit">
if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")
<textarea id="source" cols="70" rows="10" onblur="myFunction()">
say 'h';
</textarea>
<script type="text/javascript">
function myFunction() {
var source = document.getElementById('source').value;
alert(source);
}
</script>