Replace var with some new var jquery - javascript

I have code to find something from database and output it back if it exists.
Now when I output it back I need to make on click one of those outputs replace that output as var in some other var.
$(document).ready(function() {
$('#display').hide();
$("#leavepost").keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 35) {
$('#display').show();
$('#leavepost').on('keyup', function() {
var matches = $(this).val().match(/(^|\s)(#[a-z\d-]+)/ig)[0];
var name = matches;
$.ajax({
type: "POST",
url: "d/sul.php",
data: {
su: name
},
success: function(sss) {
$('#display').html(sss);
$(".adduser").click(function() {
var username = $(this).text();
var a = username;
var username2 = $(this).attr('id');
var E = "<a class='red' contenteditable='false' href='#' >" + a + "</a>";
var content = name.replace(name, E);
$("#leavepost").html(content);
$("#display").hide();
$("#leavepost").focus();
});
}
});
}).keyup();
}
});
});
When I click on class div hides but before that nothings happend... I need to replace #word from var name witdh var E.
Thanks

Your problem is most likely because you used .html() in on a <textarea> as stated in the discussion.
https://jsfiddle.net/q9gwdLj5/
$(function(){
$("#choices li").click(function(){
var name = $(this).text();
$("#ta").val($("#ta").val().replace("#thisperson", name));
})
})
Changing the .html() bit with .val() will fix the problem.

Related

How to append a div into a div with variables Javascript

I have this div here:
<div id='suggested_students'>
</div>
I am trying to write some javascript which will append this with the correct values:
<div id='STUDENT NAME' onClick='moveProfile("STUDENT NAME", "STUDENT ID")'>
STUDENT NAME<br>
STUDENT ID<br>
</div>
This is the javascript/ajax I have:
$('#search_bar').keyup(function () {
var keyword = $('#search_bar').val();
if(keyword.length > 2){
console.log('hey')
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
}
}
});
}
})
and each iteration of the for loops produces something like:
[STUDENT NAME, STUDENT ID
How do I go about filling in these place holders and then appending the html to the main div for each student.
This will add the student information into the container div for you...
success: function (data) {
// get a reference to the container div
var $container = $("#suggested_students");
// remove any existing student information
$container.empty();
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
// create a new div to add to the container element
var $div = $("<div/>");
$div.data("name", current_student[0]);
$div.data("id", current_student[1]);
$div.html(current_student[0] + "<br/>" + current_student[1]);
$div.on("click", moveProfile);
$container.append($div);
}
}
There's a couple of things worth noting here. Firstly, I didn't give each new div the ID of the student name. There are several reasons for this, but the main one is that it's not a very friendly ID. Names have spaces and can also have other punctuation marks. Also, you can have multiple students with the same name, but you can't have multiple elements with the same ID.
Secondly, I set data attributes for each student div, rather than pass the values in an inline event handler. To handle the click event you'd need this extra function, already referenced above...
function moveProfile() {
var $this = $(this);
var studentId = $this.data("id");
var studentName = $this.data("name");
// do whatever you need with the student info here
}
Try this:
$('#search_bar').keyup(function () {
var keyword = $(this).val(), $suggested_students;
$suggested_students = $('#suggested_students');
if (keyword.length > 2) {
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword
},
dataType: 'json',
success: function (data) {
var i, suggestions, s_name, s_id, current_student;
suggestions = data.students;
// empty before
$suggested_students.empty();
for(i = 0; i< suggestions.length; i++){
current_student = suggestions[i];
s_id = current_student[0];
s_name = current_student[1]
$suggested_students.append(
"<div id='" + s_id + "' onClick='moveProfile(\"" + s_name + "\", \"" + s_id +"\")'>" +
s_id + " <br>" +
s_name + " <br>" +
"</div>"
);
}
}
});
}
});
I suggest, however, to abort the $.ajax call in case a new string is written or wait a few moments before executing a new one and avoid using onClick in this way: just add a class or a selector like #suggested_students > div and add a click event listener to each div inside the container.
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
var div = "<div id='"+current_student[0]+"' onClick='moveProfile(\""+current_student[0]+"\", "+current_student[1]+")'>"+current_student[0]+"<br>"+current_student[1]+"<br></div>";
$('#suggested_students').append(div);
}

How to pass parameters to a javascript function on onclick?

I have a script where i want to call another function on onclick by passing parameters.I want to call remove_product function .How can i achieve this?
function load_cart(){
$('.mini-cart-products').html('');
var url = $('.ajax-url').attr('href');
var t = 0;
// console.log(url);
$.ajax({
url : url,
dataType:'json',
success:function(result){
if(result.length > 0)
{
var image = $('.mini-cart-image a img');
var prod_name = $('.mini-cart-name a');
var attribute = $('.mini-cart-attributes');
var pricing = $('.mini-cart-pricing');
$.each(result, function(key, val){
var remove_url = val.remove;
var barcode = val.barcode;
var cart_id = val.cart_id;
console.log("remove_url :"+remove_url+" barcode : "+barcode+" cart_id : "+cart_id);
var productDiv = $( "<div class='mini-cart-product clearfix'></div>" );
var nameDiv = '<div class="mini-cart-name font">'+val.name+'</div>';
var attributes = $( "<div class='mini-cart-attributes'></div>" );
var colorAttr = '<div class="attribute"><span class="label">Colour: </span><span class="value">'+val.color+'</span></div>';
var sizeAttr = '<div class="attribute"><span class="label">Size&nbsp&nbsp&nbsp: </span><span class="value">'+val.size+'</span></div>';
var remove = '<div class="mini-cart-remove"><a onclick="remove_product(remove_url,barcode,cart_id)">Remove</a></div>';
The line of remove var should be something like that.
var remove = '<div class="mini-cart-remove"><a onclick="remove_product(\''+remove_url+'\',\''+barcode+'\',\''+cart_id+'\')">Remove</a></div>';
This will solve your problem
Sample fiddle
You can do with html onclick:
<button onclick="myFunction(param1, param2)">Click me</button>
or via jQuery
$(button).on('click', function() {
myFunction(param1, param2);
});
Here's the same thing as other answers but without jquery: https://jsfiddle.net/7L5ypo2r/
var testButton = document.getElementById('test-button')
testButton.onclick = function(){
//your code would go here
alert("test");
};
You should declare on the top of your javascript code a member variable.
<script>
var remove_product = null;
function yourFunction () {
remove_product = 'your_value';
}
$("#yourButton").on('click', function (event) {
alert(remove_product);
}
</script>

It does not work "onclick" with attr () from JQuery

I'm trying to add an "onclick" event with their respective function from js JQuery to an interactive table td I'm doing in another .php file, the problem is not executed in the place where I want to do it but if the same instruction is executed correctly within an AJAX request a few lines below, will show you the code:
This instruction is giving me the problem:
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
And this, the function I want to run with the "onclick"
function agregar_pensum_etapa2(td,subject,level,stage){
$(document).ready(function(){
// Capture variables.
var id_periodo = $("#id_periodo").val();
var id_asignatura = subject;
var id_nivel = level;
var id_etapa = stage;
var id_mencion = null;
if (level> 3) {
id_mencion = 0;
}
// Modifiable column.
var tr = $(td).parent();
var index_td = $(td).index();
// First field
var valor_anterior = $(td).text();
$(td).html("<img src =" images / save_64.png 'width = '16' height = '16 '> & nbsp; & nbsp; & nbsp;' + '<input value = "' + valor_anterior + '" type = "text" style = "width: 40px; border: 1px solid #aaa;" onkeypress = "return soloNumeros (event);" maxlength = "2"> ');
$(td).removeAttr("onclick");
$(td).find("input").focus();
// Second field
var valor_anterior_cs = $(tr).find("td:eq("+(index_td+1)+")").text();
var checked_cs = "";
if (valor_anterior_cs === "X"){checked_cs = "checked"}
$ (tr) .find ("td: eq (" + (index_td + 1) + ")") html ("<input type = 'checkbox'" + checked_cs + ">").
// Third field
var valor_anterior_hum = $(tr).find("td:eq("+(index_td+2)+")").text();
var checked_hum = "";
if(valor_anterior_hum === "X") {checked_hum = "checked"}
$(tr).find("td:eq("+(index_td+2)+")").html("<input type = 'checkbox'"+checked_hum+">");
/ ************************************************* *********** /
$(td).find("img").click(function(){
var hora_asignatura = $(td).find("input").val();
var mencion_cs = "NO";
if($(tr).find("td:eq("+(index_td+1)+")").find("input").is ("checked")){mencion_cs = "YES";}
var mencion_hum = "NO";
if($(tr).find("td:eq("+(index_td+2)+")").find("input").is("checked")){mencion_hum = "YES";}
if(hora_asignatura === ""){
if(valor_anterior != ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+index_td+1)+")").text(valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text(valor_anterior_hum);
}else{
$(td).html("");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject +"','"+level+"','"+stage+"');");
}else if(hora_asignatura == "0"){
if(valor_anterior! = ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+(index_td+1)+")").text (valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text (valor_anterior_hum);
}else{
$(td).html("<img src =" images / diagonal.png 'height = '16' style = 'width: 15px ">");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject+"','"+level+ "','"+stage+"');");
}else{
$.ajax({
async: true,
cache: false,
dataType: "html"
type: 'POST'
url: "../Controlador/CtrlPensum.php"
data: {
id_periodo: id_periodo,
id_asignatura: id_asignatura,
id_nivel: id_nivel,
id_etapa: id_etapa,
hora_asignatura: hora_asignatura,
mencion_cs: mencion_cs,
mencion_hum: mencion_hum,
id_mencion: id_mencion,
record: "register"
},
success: function (response) {
//alert (response);
if($.trim(answer) === "1") {
$(td).html(hora_asignatura);
var marcar_cs_x = "";
if(mencion_cs === "SI"){marcar_cs_x = "X";}
var marcar_hum_x = "";
if(mencion_hum === "SI"){marcar_hum_x = "X";}
$(tr).find("td:eq("+(index_td+1)+")").html (marcar_cs_x).
$(tr).find("td:eq("+(index_td+2)+")").html (marcar_hum_x).
\\// --> HERE IT WORKS <-- \\//
$(td).attr("onclick", "agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
cargarTablaResumen ();
} Else {
alert ("Error SQL statement is not executed." + response);
}
//tr.fadeOut(500).fadeIn(500);
},
beforeSend: function () {}
Error: function (objXMLHttpRequest) {}
});
}
});
});
}
I try this:
$(td).click(function(){
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+ "','"+stage+"');");
});
And in the html it prints correctly but does not work, like he was not the "onclick" there. And the function if it works, I put the onclick to that function when I load the page and if it works, but when I click the td and give back to click to restore does not restore the onclick.
Instead of setting the onclick attribute, why not do use .click() again with closures? So your code would be something like...
$(td).click(function(){
var td = this;
$(td).click(function () {
agregar_pensum_etapa2(td,subject,level,stage);
});
});
Do you write
$(Document)
Instead of $(document) with small letter "d".

How do I scroll down a chatbox (div) automatically?

I've been working on a chat application and now I need to scroll automatically when a message appears.
I've tried different things but they do not work unfortunately.
So this is my main.js code:
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "/refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
var message = $('#view_ajax');
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div>(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
message.html(data);
message.scrollTop(message[0].scrollHeight);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "/submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
I've used
var message = $('#view_ajax');
message.html(data);
message.scrollTop(message[0].scrollHeight);
I really have no clue how jQuery works. I've tried a couple of things before this but it didn't work also.
Do you have any suggestion? Any advice?
Do you need any more information? Feel free to ask!
Give each message an ID, as follows:
<div id="msg-1234">
Then you can scroll to this element using this jQuery:
$('html, body').animate({ scrollTop: $('#msg-1234').offset().top }, 'slow');
Alternatively, put a div at the bottom of your chat:
<div id="chat-end"></div>
And scroll to this ID instead.
JSFiddle Demo

Onchange Ajax method to load values from database work correct but how to change textarea value multiply with another textbox value

I'am using Ajax call to load on-change value from database into text-area with all values and their quantity in one text-area. Now I want to change this text-area value to change when I entered a value in another text-box and multiply with all quantity value of text-area.
I am new to JavaScript and ajax so help me guys. Here is my code.
$(document).ready(function () {
$('#location').change(function () {
$.ajax({
url: 'location.php?location=' + $(this).val(),
type: "get",
timeout: 10000,
dataType: 'json',
success: function (data) {
var material_name = data.material_name;
var material_quantity = data.product_quantity;
var data_material = "";
for(var i = 0; i < material_name.length; i++) {
data_material += material_name[i] + " : " + material_quantity[i] + " ";
}
document.getElementById("material_name").value = data_material;
document.getElementById("material_quantity1").value = data.product_quantity;
},
error: function () {}
});
$('#quantity').keyup(function () {
var price = document.getElementById('material_quantity').value;
//document.getElementById("price_hidden").value=price;
var quantity = document.getElementById("quantity").value;
var total = quantity * price;
document.getElementById("total").value = total;
document.getElementById("total_hidden").value = document.getElementById("total").value;
});
});
});
I want to change all values of text-box with ID #material_quantity1 value when I entered any quantity in other text-box.
Like in my textbox I have 15,20,25 now if I entered 5 then it will show 75,100,125.
$('#textarea1').live('blur',function(){ // Textarea in which you will enter the value..
var textarea1 = $('#textarea').val(); // Textarea which will contain 152025..
// if your value containts commas then you can use $('#textarea').val().replace(/,/g , ""); instead of $('#textarea').val();
var final_value = $(this).val()*textarea1; // Put this value in the textarea you want...
});
//Add the below function this will replace your numbers with commas
function ReplaceNumberWithCommas(param1) {
var x=param1.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
return res;
}

Categories