I want to display first 10 characters afterword ... till .pdf or xlx or .docx match. Each result has link . when user click on perticular link it will redirect to matching file and file will be download. could anyone help me.
function createRowMultiresult(jobjects) {
var $div = $('<div class="chat Bot"></div>');
var $div2 = $('<div class="user-photo"><img src="{% static "Robot.jpg" %}" /></div>');
$div.append($div2);
var $tbl = $('<table style="width:100%;"></table>');
if (jobjects.length>1){
var $tr = $('<tr><td style="padding:5px;">Multiple results Found for your query. Please search with specific keyword</td></tr>');
$tbl.append($tr);
}
for(var x=0; x<jobjects.length;x++){
var currentobj = jobjects[x];
if (currentobj.ans != null){
if (currentobj.ans.indexOf("/AA") != -1){
var $tr = $('<tr><td style="padding:5px;"><a href="https://' + currentobj.ans +'" target="_blank" >Click Here for User Guide</a></td></tr>');
$tbl.append($tr);
}
else{
var $tr = $('<tr><td style="padding:5px;">' +(x+1)+'.'+ currentobj.ans.replace(/[^\w\s]/gi, "<br/>") +'</td> </tr>');
$tbl.append($tr);
if (currentobj.Pic.length>7){
var $tr = $("<tr><td style='text-align:center;'><img class='productpic' src='{% static '/Pictures/' %}" + currentobj.Pic +"' /></td></tr>");
$tbl.append($tr);
}
}
}
else if(currentobj.filename != null){
alert("Got there");
var $tr = $('<tr><td style="padding:5px;"><a href="https://' + currentobj.ans + '" target="_blank" >' + currentobj.filename.slice(0,10)+"...."+ +'</a></td> </tr>');
$tbl.append($tr);
}
}
var $par = $('<p class="chat-message"></p>');
$par.append($tbl);
$div.append($par);
$chatlog.append($div);
}
Each result has link.
Sample actual result:
insert_data_data_data.pdf
BE_guage_data_data.xlsx
BE_guage_data_data.docx
Expected output and when user click it will download :
insert_data....pdf
BE_guage.....xlsx
BE_guage.....docx
You can simply count character length and replace '...' after some point.
var displayName = ( currentobj.ans.length > 10 ) > ( currentobj.ans.substring( 0, 10 ) + '...' ) : currentobj.ans;
Now you can use this displayName variable for display.
in .substring() function first parameter is the starting point, and the second one is the endpoint.
According to the samples and the expected outputs, the simplest way is by using the replace function i.e.
result_str.replace(/_data_data\./, '...')
You can use a regex with capture groups. $n is the nth group.
var regex = /(\w{10})\w+(\.\w+)/;
var str = "insert_data_data_data.pdf";
console.log(str.replace(regex, "$1...$2"));
Related
I am unable to get the href link of anchor. I created elements dynamically in loop in jquery. Please help me out how to get the link address.
function setGrid(){
// get List of all Avatars...
var arr = ['MMA','MMB','MMC','MMD','MME','MMF','MMG','MWA','MWB','MWC','MWD','MWE','MWF','MWG'];
for(var i=0;i<arr.length;i++)
{
var d = "<a class='testClick' href='../../images/avatars/"+arr[i]+".png'>"+
"<img src='../../images/avatars/"+
arr[i]+".png' id='"+arr[i]+"' alt='avatar' style='height:120px;width:120px; margin-left:10px'></a>";
$( "div.modal-body" ).append( d );
}
}
Below is how I'm trying to access the link with onclick listener:
$(document).ready(function(){
$(".testClick").click(function () {
var value = $(this).attr('href');
alert(value );
});
});`
I'm unable to get the href. Please help me out.
Your above code works fine; it correctly alerts out the href attribute.
The only thing you're missing is to prevent the click actually taking you to that link. This can be done by passing e into your .click() function for .testClick, and then calling e.preventDefault() to prevent the default click behaviour:
function setGrid() {
// get List of all Avatars...
var arr = ['MMA', 'MMB', 'MMC', 'MMD', 'MME', 'MMF', 'MMG', 'MWA', 'MWB', 'MWC', 'MWD', 'MWE', 'MWF', 'MWG'];
for (var i = 0; i < arr.length; i++) {
var d = "<a class='testClick' href='../../images/avatars/" + arr[i] + ".png'>" +
"<img src='../../images/avatars/" +
arr[i] + ".png' id='" + arr[i] + "' alt='avatar' style='height:120px;width:120px; margin-left:10px'></a>";
$("body").append(d);
}
}
setGrid();
$(document).ready(function() {
$(".testClick").click(function(e) {
e.preventDefault();
var value = $(this).attr('href');
alert(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
fI'm developing a simple and small search in a Wordpress page using a $_GET variable in the url passed by javascript:
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = document.URL+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
So, the url to search is: MYURL/?page_id=51&pesquisa=test
Of course, the page_id is variable. If I search again, the URL is going to be: MYURL/?page_id=51&pesquisa=test&pesquisa=new, what is wrong.
How could I get just the MYURL/?page_id=51 using javascript? The window.location.pathname is not what I need.
Thanks.
Anything that searches naively will be vulnerable to problems like this: What if the URL is:
http://example.com/?pesquisa=test&page_id=51
You need to search for and remove the relevant query parameter:
var caminho = document.URL.replace(/([?&])pesquisa=[^&]+&?/,"$1")+"&pesquisa="+pesquisar;
Try this hopefully it should work
<script>
function pesquisar()
{
var pesquisar = document.getElementById('termo').value;
var caminho = location.protocol + '//' + location.host + location.pathname+'&pesquisa='+pesquisar;
window.location = caminho;
}
</script>
<input type='text' id='termo'>
<input type='button' value='pesquisar' onclick='pesquisar()'>
try this.
var a = document.URL;
var result = a.substr(0, a.indexOf('&'));
Resources:
Get current URL in web browser
how to grab substring before a specified character jquery or javascript
javascript:
<script type="text/javascript">
function get_query_param(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
window.onload = function() {
if (get_query_param("page_id") != null) {
alert(window.location.pathname + "?page_id=" + get_query_param('page_id'));
}
}
</script>
hope that helps.
I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here
feel like im coming here way too often to ask questions but yet again I am stuck. I am attempting to select a textarea and allow myself to edit the text in another textarea, which works fine using textboxs but not with textareas. Every time I click on the div container I am getting an undefined result when looking for the textarea. Below is the code.
jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id') should be returning textbox1(or similar) but instead just returns undefined.
I have tried .find(':textarea'),.find('textarea'),.find(text,textArea),.find(':input') and quite a few others that I have found through google but all of them return undefined and I have no idea why. A demo can be found here, http://jsfiddle.net/xYwaw/. Thanks in advance for any help guys, it is appreciated.
EDIT: Below is the code for a very similar example I am using. This does what I want to do but with textboxs instead of textareas.
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
First up remove the second parameter, 'div', from the first line:
$(".textAreaContainer").live('click','div', function(){
...to make it:
$(".textAreaContainer").live('click', function(){
Then change:
var t = $('#' + divID ).find(':input');
...to:
var t = $(this).find(':input');
Because you already know that this is the container so there's no need to select it again by id. Also the id attributes that you're assigning to your textarea containers have a space in them, which is invalid and results in your original code trying to select the element with '#textAreaContainer 0' which actually looks for a 0 tag that is a descendant of #textAreaContainer. So fixing the code that creates the elements to remove that space in the id is both a good idea in general and an alternative way of fixing this problem.
I have these links :
Block 1 :
Adapters
Battery
After click on the link in Block1 , then I start to click on Block2:
Block 2 :
<img src ="/Content/Images/Top/searchbutton.png"/>
I can get the parameter value such as dep=56,cat=654 by using these jquery.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null){
return "";
}else{
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function SearchClick() {
var cur_url = window.location.href;
var depId = getParameterByName("dep");
var catId = getParameterByName("cat");
var searchStr = getParameterByName("search");
var url_add = "";
if (depId != "") {
url_add += "&dep=" + depId;
}
window.location = "/Products?tab=2"+ url_add;
}
But now I exchanged the link in Block 1 with
<a href='javascript:void(0);' dep='" + work.ID + "'>" + work.ProName + "</a>
//it works well
So how can I get the value of dep in Block 1 by using javascript or jquery when I click on the the Block 2 link?
Thanks so much for all your answers.
It would be best if you put an ID on the A tag, like so:
<a id="myLink" href='javascript:void(0);' dep='" + work.ID + "'>" + work.ProName + "</a>
then you could use the following JQuery to get the value of work ID:
$("#myLink").attr("dep")
or plain old Javascript like so (assuming you've still got that ID on the A tag):
document.getElementById("myLink").getAttribute("dep")
EDIT: I've put it in the click for you, here is all my code:
<a id="block1Link" href='javascript:void(0);' dep="56">Adapters</a>
<br />
<br />
Click
<script type="text/javascript">
function SearchClick() {
var department = $("#block1Link").attr("dep");
alert(department);
}
</script>
Or if you want to use Javascript swap the var department line with this line:
var department = document.getElementById("block1Link").getAttribute("dep");