How to get function arguments' text value in js? - javascript

I find some code:
<a onclick="return dosomething('1234567')"></a>
I want to get the "1234567", Is there anyway to get it without Regular expressions ?
The code is in the html on www.xxxxxxxx.com and I can't change, the argument in dosomething function is data used as id.I want collect the id information.
So the html might be
<a onclick="return dosomething('1')"></a>
<a onclick="return dosomething('2')"></a>
<a onclick="return dosomething('3')"></a>
<a onclick="return dosomething('4')"></a>
I want run some js code in browser's console to get data like "1","2","3","4"
I have used jquery get the html like
$("a")
Then I don't know how to get the argument in "dosomething function". It is only a text to me.

Try this
$(function () {
var txt = $('a[onclick^="return dosomething("]').map(function () {
return this.getAttribute('onclick').match(/'.*'/)[0];
}).get().join(",");
alert(txt);
});
EDIT: without RegExp
$(function () {
var txt = $('a[onclick^="return dosomething("]').map(function () {
var attr = this.getAttribute('onclick');
return attr.substring(attr.indexOf("'"), attr.lastIndexOf("'") + 1);
}).get().join(",");
alert(txt);
});

try this
$(document).ready(function(){
var new_text = "";
$("a").each(function(){
var str = $(this).attr("onclick");
var newtext = str.substring(str.lastIndexOf("(")+1,str.lastIndexOf(")"));
if(new_text=="")
new_text += newtext;
else
new_text += ","+newtext;
});
alert(new_text);
console.log("New Text : "+new_text);
});
FIDDLE DEMO

Related

Getting error when truing to save value from input to localStorage

Getting error when truing to save value from input to localStorage
res.html is not a function
Here is my code:
Enter Text: <input type="text" id="inp" onchange="myFunction()">
<div id="result"></div>
<script>
var inp = document.getElementById('inp');
var res = document.getElementById('result');
function myFunction() {
var str = res.innerHTML = inp.value;
localStorage.setItem('value', str);
if(localStorage.getItem('value')) {
res.html(localStorage.getItem('value'));
}
}
.html() is a JQuery function not a JavaScript one. To achieve what you're doing using JavaScript, you would use .innerHTML. So for example:
res.innerHTML = localStorage.getItem('value');
You wanted to use innerHTML instead of html(). That's a jQuery function.
res.innerHTML = localStorage.getItem('value');
It is not localStorage issue. html is not a defined function in DOM
You can do:
if(localStorage.getItem('value')) {
res.innerHTML = localStorage.getItem('value');
}

JavaScript convert string hrefs into onClicks

I've got strings with multiple standard links like
Name of Link
and I'm trying to turn them into
<a onClick="myFunc('http://example.com','Name of Link')">Name of Link</a>
or even just:
<a onClick="myFunc('http://example.com')">Name of Link</a>
would be great if the former was unnecessarily difficult. The links are being dynamically inserted into the DOM so event handlers won't do.
You need event handlers that prevents the default action and get the href
var anchors = document.getElementsByTagName('a');
for (var i=anchors.length; i--;) {
anchors[i].addEventListener('click', func, false);
}
function func(e) {
e.preventDefault();
var href = this.getAttribute('href'),
text = this.innerText;
myFunc(href, text);
}
FIDDLE
If you have to work with strings, you can do something like this
var str = 'Name of Link 1<br />Name of Link 2<br />Name of Link 3<br />Name of Link 4';
var parser = new DOMParser();
var doc = parser.parseFromString(str, "text/html");
var anchors = doc.getElementsByTagName('a');
for (var i=anchors.length; i--;) {
var href = anchors[i].getAttribute('href'),
text = anchors[i].innerText;
anchors[i].setAttribute('onclick', "myFunc('"+href+"', '"+text+"')");
anchors[i].removeAttribute('href');
}
str = doc.body.innerHTML;
document.body.innerHTML = str;
function myFunc(href, text) {
alert(href + ' - ' + text);
}
You can do like this
HTML
<a href="http://example.com" onclick="myFunction(this.href,this.textContent)">
My link
</a>
JS
function myFunction(getAttr,text){
console.log(getAttr,text);
}
EXAMPLE
EDIT
if you are looking to prohibit href action then you have to use
event.preventDefault();
Updated JS
function myFunction(event,getAttr,text){
event.preventDefault();
console.log(getAttr,text);
}
UPDATED JSFIDDLE
Append your string in a temporary element and manipulate it as explained by adeneo
Try this:
var str = 'Name of Link';
var elem = document.createElement('div');
elem.innerHTML = str;
var targetEleme = elem.getElementsByTagName('a')[0];
targetEleme.addEventListener('click', function(e) {
e.preventDefault();
var href = this.getAttribute('href'),
text = this.innerText;
myFunc(href, text);
});
document.body.appendChild(targetEleme);
function myFunc(href, text) {
alert('HREF: ' + href + ' TEXT: ' + text);
}
Fiddle here

Add Text to input On Click

I want to type kappa in input on image click. I have this code but it seems like it doesn't work...
document.getElementById("kappa").addEventListener('click', function () {
var text = document.getElementById('usermsg');
text.value = (text.innerHTML + ' kappa ');
});
<img src='http://placehold.it/50x50' width='100px'>
<br>
<input type="text" id="usermsg">
Where did I made a mistake? And how can I solve it?
Use value instead of text:
document.getElementById("kappa").addEventListener('click', function () {
var text = document.getElementById('usermsg');
text.value = (text.value + ' kappa ');
return false;
});
And give a return false to make it not follow the link.
Fiddle: http://codepen.io/anon/pen/QjELxJ
do the following:
document.getElementById("kappa").addEventListener('click', function(evt) {
document.getElementById("usermsg").value = "kappa";
});

How can I create a link based on this format: google->someword?

I want to create links, based on a specific format.
When I type this:
google->apple
I want get get this link:
https://www.google.hu/search?q=apple
I tried this way, but unfortunately it is not working:
//Intelligent actions start
function replace(){
var str = $('.smile').html();
var re = /google->([^ \n$]+)/g;
var url = "https://www.google.hu/search?q=" + re.exec(str)[1];
}
//Intelligent actions end
Update
Based #vinayakj answer, I start create a solution for this:
//Intelligent actions start
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
//location.href = url;
}
$( document ).ready(function() {
googleSearch($('.comment-content p').text())
$( ".comment-content p" ).replaceWith( "<a href='url'>url</a>" );
});
//Intelligent actions end
And looks like replacewith function reaplce all content in
.comment-content p
with:
url
And this function it has some problem:
Reaplce all text even if dosen't find this sting in div:
google-->some word
The link is absolute incorrect becouse I get back this value everywhere:
url
What am I doing wrong?
function googleSearch(val){
var url = "https://www.google.hu/search?q=" + val.split('->')[1];
alert(url)
location.href = url;
}
<input onchange="googleSearch(this.value)" type=text>
Here is the final solution after all your comments
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
var url = urls[parts[0]].replace("#",encodeURI(parts[1]));
return = $("<a/>",{href: url, class:parts[0]+"-search"}).text("Keresés ..."+parts[1]);
}
$(function() {
$("div.comment-content > p.smile").each(function() {
var $link = getLink($(this).text());
$(this).html($link);
});
});
Old answer
var urls = {
"google":"https://google.com/search?q=#",
"bing":"https://....q=#&bla=bla"};
function getUrl(str) {
var parts = str.split("->");
return urls[parts[0]].replace("#",parts[1]);
}
window.onload=function() {
document.getElementById("myForm").onsubmit=function() {
var str = document.getElementById("q").value;
var url = getUrl(str);
if (url) alert(url); // location.href=url;
return false; // cancel the submit
}
}
<form id="myForm">
<input id="q" type="text">
</form>
I found the solution, but thanks for everybody:
$("div.comment-content > p.smile").each(function(){
var original = $(this).text();
var replaced = original.replace(/google->([^.\n$]+)/gi, '<a class="google-search" href="https://www.google.hu/search?q=$1" target="_blank">Keresés a googleben erre: $1</a>' );
$(this).html(replaced);
console.log("replaced: "+replaced);
});
$("a.google-search").each( function() {
this.href = this.href.replace(/\s/g,"%20");
});

Javascript results to div

Q1: My point is create many buttons as many rows of array. Like this, only one button appears.
<script type="text/javascript">
var myArray = [];
$('#button').click(function(){
var value1 = $('#value1').val();
var value2 = $('#value1').val();
var value3 = $('#value1').val();
var newArray = [];
var newArray[0] = value1;
var newArray[1] = value2;
var newArray[2] = value3;
myArray.push(newArray);
$("#save").append(
$("<button>").click(function() {
myFunction.apply(null, myArray);
}).text("Click me!")
);
});
});
function myFunction(value1,value2,value3)
{
var jsonData = $.ajax({
url: "file.php?value1=" + value1 + "&value2=" + value2 + "&value3=" + value3
dataType: "json",
async: false
}).responseText;
(...)
}
//edited: problem maybe found. I said buttons dont do anything because of this.
OUTPUT: file.php?value1=paul,23,USA&value2=undefined&value3=undefined
//it seems that value1 gets all values :s
</script>
<div id ="save"></div>
Im looking for a solution that return someting like this:
eg:
<!--<button onclick="myFunction(name,age,country)">Click me</button>-->
<button onclick="myFunction(paul,23,USA)">Click me</button>
<button onclick="myFunction(john,23,USA)">Click me</button>
EDITED MY CODE WITH MORE DETAILS
.html replaces, and your quotes are mismatched. But it doesn't matter - jQuery is better at manipulating the DOM than it is at manipulating strings. Try:
$("#save").append(
$.map(myArray, function(item) {
return $("<button>").click(function() {
myFunction.apply(null, item);
}).text("Click me");
})
);
Here's a demo.
You're only seeing one button because the .html() method replaces the html of the element. It doesn't append.
Luckily, jQuery has a method for the behavior you want, fittingly called append. Change it to look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>");
$("#save").append(button) ;
}
I intentionally left the onclick behavior out of that snippet. You can write it in the html of the button you create, as you have been, or you can do it with jQuery - the second method is preferable, and would look like this:
for(i=0;i<myArray.length;i++)
{
var button = $("<button>Click me</button>")
.click(function(){
// call the actual function you want called here
});
$("#save").append(button);
}
Did you mean this:
<div id="save">
</div>
<script type="text/javascript">
function addButtons(){
for(i=0;i<myArray.length;i++)
{
var button = $('<button id="btn_'+i+'" onclick="myFunction(this);">Click me</button>')
$(button).data('details',myArray[i]).appendTo("#save");
}
}
function myFunction(element){
alert($(element).data('details'));
}
</script>
This is because you are replacing the html in the $("#save") in the loop . Try
$("#save").append("<button onclick="myFunction('"+myArray[i]+"')">Click me</button>") ;
for(i=0;i<myArray.length;i++){
//Create a new DOM button element ( as jQuery object )
// Set the current button index, and add the click action
var button = $('<button />').data('myindex', i).click(function(){
var myArrayItem = myArray[$(this).data('myindex')];
alert(myArrayItem);
}).html('My label n. '+i);
$('#save').append(button)
}
Why bothering with all the JQuery and complicated code, just use simple way to implement this
<script type="text/javascript" >
var myArray = ["New York", "Boston", "San Jose", "Los Angeles"];
var strHTML = "";
for(i=0;i<myArray.length;i++)
{
strHTML += "<button onclick='myFunction("+i+")'>Click me</button>";
}
$("#save").innerHTML = strHTML;
function myFunction(index)
{
alert(index);
// do your logic here with index
}
</script>

Categories

Resources