Replace div element not working in JQuery? - javascript

In my use case I have question title and question text labels. When I press edit button I want replace the labels with Text boxes with question title and question text. Also submit and cancel buttons for edit. In this edit if I press cancel I should replace with original div content. The following code is working until cancel. When I press cancel it is not properly replacing the original content. Also the edit button got disabled. I didn't disable edit button anywhere manually.
JQuery code:
//global variable for question edits
var originalQuestion = "";
//Enables and disables the question elements
//for all questions
$('.questiondiv').on('click', '.edit_question_button', function() {
console.log("In submit edit question text area");
var pageURL = $('#page_url').text();
var loggedUser = $('#logged_user').text();
if (!loggedUser) {
console.log("In answerbutton redirect");
window.location.href = "/login/?redirect="+pageURL;
} else {
console.log("question edit");
title_val = $(this).closest('.question-inner').find('.quest_title_val').text();
question_val = $(this).closest('.question-inner').find('.quest_text_val').text();
console.log("question edit logged in 2");
console.log("Question title value ", title_val);
console.log("Question value ", question_val);
newdiv = "<div class='form-input updated_question'><input name='question_title_val' class='question_title_val' type='text' size='81' value='"+title_val+"' /></div> <br /> <div class='form-input'><textarea name='question_text_val' class='question_text_val' rows='8' cols='80'>"+question_val+"</textarea><br /><div class='form-input'><a type='Submit' id='updatequestion' name='updatequestion' class='btn btn-primary updatequestion'>Update Question</a><a type='Cancel' id='cancelupdatequestion' name='cancelupdatequestion' class='btn btn-primary cancelupdatequestion'>Cancel</a></div></div>";
originalQuestion = $(this).closest('.questiondiv').html()
$(this).closest('.question-inner').replaceWith(newdiv);
}
});
//updates question
//question ID may have to added as
//hidden element in the html
$('.questiondiv').on('click', '.updatequestion', function() {
console.log("In update question button");
var question_id = $(this).closest('li').find('.question_id_val').val();
var quest_title = $(this).closest('.updated_question').find('.quest_title_val').text();
var quest_val = $(this).closest('.updated_question').find('.quest_text_val').text();
console.log(quest_title);
console.log(quest_val);
$.getJSON("/question?question_id="+question_id+"&question_title"+quest_title+"&question_val="+quest_val, function(data) {
console.log("update question Response "+data);
$(this).closest('.updated_question').replaceWith(originalQuestion);
});
//$(this).closest('.answersectiondiv').remove();
});
//cancel updatequestion elements
$('.questiondiv').on('click', '.cancelupdatequestion', function() {
console.log("In cancel update question area");
//console.log("Original question div tag ", originalQuestion)
$(this).closest('.question-inner').replaceWith(originalQuestion); //Again use this to remove only parent container div
//$(this).closest('.questiondiv').find('.edit_question_button').prop( 'disabled' , true );
});
HTML code:
<div class="qanda questiondiv" id="questionarea" name="questionarea">
<div class="question-inner">
<div>
<div id="topic" class="upvote pull-left">
<a class="upvote"></a>
<span class="count">3</span>
<a class="downvote"></a>
</div>
<div >
<div class="qanda-info">
<h6><p class="quest_title_val">{{.QuestionTitle}}</p></h6>
</div>
<p class="quest_text_val">{{.QuestionText}}</p>
</div>
</div >
<div class="qanda-info">
<div class="user-info">
<a href="/userprofile/{{.UserId}}" ><img src="http://tinygraphs.com/spaceinvaders/Dany?theme=frogideas&numcolors=4&size=220&fmt=svg"/>
</a>
</div>
<h6>{{.UserId}}</h6>
<span class="date alt-font sub">{{.DateCreated}}</span>
[<a class="edit_question edit_question_button" >edit</a>|<a class="delete_question_button" id="deleted" ">delete</a>]<br>
<a id="answertext" name ="answertext" type="submit" class="link-text answerbutton">Answer</a>
</div>
</div>
</div>
Could someone help me with this? Thanks

Related

Second execution follows href

With a list of products, and once a 'remove from wishlist' button is clicked, it then removes that product from said product list, along with an AJAX request to the back-end for it to be removed via SQL.
The first click works, the jQuery executes and the product is then removed. The second click on the same type of button for any product, then loads the href instead of executing the jQuery, it's meant to execute the jQuery.
I've tried calling it as a static function from the anchor onclick="return removeFromWishlist();"
Have also tried executing the jQuery on the anchor link click via the jQuery event instead of the button tag itself.
jQuery('.button-wishlist').on('click', function (index) {
event.preventDefault();
// Calls the AJAX to remove it from the back-end via SQL etc
// The response is JSON within the following call
removeProductAjax(this);
console.log('removing product from the wishlist');
// Get the cell position of the product to remove from the wishlist
var position = jQuery(this).parent().parent().parent().data('cell');
var html = [];
var cells = 0;
jQuery('.wishlist_container .col-md-4').each (function () {
//
if (jQuery(this).data('cell') == position) {
cells++;
}
else if (jQuery(this).data('cell') !== undefined) {
html.push(jQuery(this).html());
cells++;
}
});
var upto = 0;
jQuery('.product-row').each (function () {
var self = this;
// Repopulate all the product lists excluding the one removed
jQuery(self).children().each (function () {
jQuery(this).html(html[upto]);
upto++;
});
});
// Then clear everything from upto and onwards!
console.log('cells: ' + cells);
console.log('upto: ' + upto);
// let's change from array to 'standard' counting
upto--;
// Remove the last element!
jQuery('.product-row').find('[data-cell=' + upto + ']').remove();
// Check for any empty rows
jQuery('.product-row').each (function () {
if (jQuery(this).children().length == 0) {
jQuery(this).remove();
}
});
});
The HTML is basically:
<div class="row product-row">
<div class="row product-row"><div class="col-md-4" data-cell="0">
<h1>product 1</h1>
<a href="./page.php?page=cart&unwish=660986" data-index="660986" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="1">
<h1>product 2</h1>
<a href="./page.php?page=cart&unwish=661086" data-index="661086" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
<div class="col-md-4" data-cell="2">
<h1>product 3</h1>
<a href="./page.php?page=cart&unwish=661067" data-index="661067" class="wishlist-button" onclick="return removeProductFromWishlist(this);">
<button name="wishlist" class="btn button-wishlist" data-type="remove">Remove from Wishlist</button>
</a>
</div>
</div>
I'm expecting it to execute the jQuery each time the "remove from wishlist" button is clicked, no matter what product, no matter what order. So, you can unwish many products, one after the other using AJAX / jQuery.
Follow all my comments under your Question...
And I think this is all the code you need.
PHP (I used i.e: ../removeProduct.php?id=) should respond with some JSON like:
// PHP does here some DB deletions or fails.
// Send back to AJAX the deleted item ID (or null)
// and some (error?) message
echo json_encode(['id' => $id, 'message' => $message]);
exit;
// No more PHP here. We exit.
// jQuery will collect that JSON response as `res`
jQuery(function($) {
function removeProductAjax(id) {
$.get("../removeProduct.php?id=" + id, 'json').always(function(res) {
if (res.statusText === 'error') { // General error (path invalid or something...)
return alert(`Error: Cannot remove product ID: ${id}`); // and exit function
}
if (!res.id) { // Something happened
return alert(res.message); // Alert PHP's error message and exit function.
}
// All OK. Remove item from products
$(".product-row").find(`[data-id="${res.id}"]`).remove();
});
}
$('.product-row').on('click', '.product-remove', function(ev) {
ev.preventDefault();
removeProductAjax($(this).data('id'));
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="row product-row">
<div class="col-md-4" data-id="660986">
<h3>product 1</h3>
<button type="button" class="btn product-remove" data-id="660986">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661086">
<h3>product 2</h3>
<button type="button" class="btn product-remove" data-id="661086">Remove from Wishlist</button>
</div>
<div class="col-md-4" data-id="661067">
<h3>product 3</h3>
<button type="button" class="btn product-remove" data-id="661067">Remove from Wishlist</button>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

Select a button by its value and click on it

How can I select a button based on its value and click on it (in Javascript)?
I already found it in JQuery:
$('input [type = button] [value = my task]');
My HTML Code for the Button is :
<button type="submit" value="My Task" id="button5b9f66b97cf47" class="green ">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Lancer le pillage</div>
</div>
<script type="text/javascript" id="button5b9f66b97cf47_script">
jQuery(function() {
jQuery('button#button5b9f66b97cf47').click(function () {
jQuery(window).trigger('buttonClicked', [this, {"type":"submit","value":"My Task","name":"","id":"button5b9f66b97cf47","class":"green ","title":"","confirm":"","onclick":""}]);
});
});
</script>
What is the equivalent in JS and how may i click on it
(probably like this: buttonSelected.click(); ) .
And how do i run the javascript of the button clicked ?
Use querySelector to select it. Then click()
Your HTML has a button and not an input element so I changed the selector to match the HTML.
let button = document.querySelector('button[value="my task"]');
button.click();
<button type="submit" value="my task" id="button5b9f54e9ec4ad" class="green " onclick="alert('clicked')">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Launch</div>
</div>
</button>
Otherwise, use this selector:
document.querySelector('input[type="button"][value="my task"]')
Note that if you have multiple buttons with the same value you'll need to use querySelectorAll and you'll get a list of all the buttons.
Then you can loop over them and click() them all.
Edit - new snippet after question edit
jQuery(function() {
jQuery('button#button5b9f66b97cf47').click(function() {alert('success')});
document.querySelector('button[value="My Task"]').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="submit" value="My Task" id="button5b9f66b97cf47" class="green ">
<div class="button-container addHoverClick">
<div class="button-background">
<div class="buttonStart">
<div class="buttonEnd">
<div class="buttonMiddle"></div>
</div>
</div>
</div>
<div class="button-content">Lancer le pillage</div>
</div>
you can try:
var elements = document.querySelectorAll("input[type = button][value=something]");
note that querySelectorAll returns array so to get the element you should use indexing to index the first element of the returned array and then to click:
elements[0].click()
and to add a event listener u can do:
elements[0].addEventListener('click', function(event){
event.preventDefault()
//do anything after button is clicked
})
and don't forget to add onclick attribute to your button element in html to call the equivalent function in your javascript code with event object
I am not recommended this way because of excess your coding but as you mentioned, below are the equivalent way.
$(document).ready(function() {
var selectedbuttonValue = "2"; //change value here to find that button
var buttonList = document.getElementsByClassName("btn")
for (i = 0; i < buttonList.length; i++) {
var currentButtonValue = buttonList[i];
if (selectedbuttonValue == currentButtonValue.value) {
currentButtonValue.click();
}
}
});
function callMe(valuee) {
alert(valuee);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<input type="button" class="btn" value="1" onclick="callMe(1)" />
<input type="button" class="btn" value="2" onclick="callMe(2)" />
<input type="button" class="btn" value="3" onclick="callMe(3)" />
Using JavaScripts querySelector in similiar manner works in this case
document.querySelector('input[type="button"][value="my task" i]')
EDIT
You might save your selection in variable and attach eventListener to it. This would work as you desire.
Notice event.preventDefault() -function, if this would be part of form it would example prevent default from send action and you should trigger sending form manually. event-variable itselfs contains object about your click-event
var button = document.querySelector('input[type="button"][value="my task" i]')
button.addEventListener('click', function(event){
event.preventDefault() // Example if you want to prevent button default behaviour
// RUN YOUR CODE =>
console.log(123)
})

Retrieve newly updated article without refreshing the page

I'd like to make a edit link to update the article when it's clicked,
In the template, it's structured as:
post-text
article-content
article-form
post-menu
I hide "article-form" in first place as <div class="article-form" style="display: none;"> until edit link is clicked.
<div class = "col-md-12 post-text" >
<div class="article-content">
{{article.content}}
</div>
<div class="article-form" style="display: none;">
<form class="form-horizontal" action="/article/edit/{{ b.id }}" method="POST">
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control" id="editContent" name="content" rows="10" cols="30">
{{form.content.value}}
</textarea >
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-0 col-sm-12">
<button type = "submit" class = "btn btn-success btn-sm" id = "saveEditBtn"> Save Edits </button>
</div>
</div>
</form>
</div><!-- article-form -->
</div>
<div class="post-menu pull-left">
<a id="editArticleLink" href="{% url 'article:article_edit' article.id %}">
<span class="glyphicon glyphicon-edit" aria-hidden="true">edit </span>
</a>
<a id="delArticleLink">
<span class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</div>
After updating is completed and submit is cliked, send data to backend using Ajax, hide "article-form" and show "article-content".
<script>
$(document).ready(
$(".post-menu a").on("click", function(e){
e.preventDefault();
//retrieve the topmost element which the target lives in
$postText = $(e.target).closest(".post-text");
//hide article-content
$postText.find(".article-content").hide();
//show the article-form for users to update
$postText.find(".article-form").show();
//capture the button submitting event
$(".article-form button").on("click", function(e){
var content = $postText.find("textarea").val();
$.ajax({
type:"POST",
url: ,
data:,
success: function(){
//if saved successfully
$postText.find(".article-content").show();
$postText.find(".article-form").hide();
},//success
})//ajax post request
});//nested button click event
}) //click event
)//ready
</script>
My problem is that in ajax success,
$postText.find(".article-content").show() still display the non-updated article,
How could I retrieve the updated without refreshing the page?
If you can send the edited version to server... You have the new content! Update the .article-content with it then show.
Here is what I think it is...
//capture the button submitting event
$(".article-form button").on("click", function(e){
var content = $postText.find("textarea").val();
$.ajax({
type:"POST",
url: ,
data:, // <-- There is something missing here... I assume it's content.
success: function(){
//if saved successfully
$postText.find(".article-content").html(content).show(); // update before the show!
$postText.find(".article-form").hide();
},//success
})//ajax post request
});

JQuery or JavaScript - get name of btn clicked

I have a quiz like slideshow that dynamically generates the questions and the list of answer options.
The answer options are of input type button and are generated dynamically from a table. The button name is also dynamically generated. The number of answer options is dymamic.
When a user clicks on an answer option I need to capture the name of the button.
I have tested out several interations of my code but am not successfully capturing the button clicked. Any input, insight is greately appreicated. Code is below. Just a quick callout - the HTML works without issue. I am using AMPSCRIPT for a Salesforce Makreting Cloud pages.
function btnAnswer(){
var btnClicked = $('.slide :button[clicked]');
var btnValue = $(btnClicked).val();
var btnName = $(btnClicked).attr("name");
var btnQuestion = btnName.substring(0, btnName.indexOf('A'));
btnQuestion = btnQuestion.substring(btnQuestion.indexOf('Q') + 1);
var btnAnswer = btnName.substring(btnName.indexOf('A') + 1);
updateScore(btnQuestion, btnAnswer);
}
<!-- begin snippet: js hide: false console: true babel: false -->
<div class="slide">
<p class="question-p">%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'QuestionBackground'))=%%</p>
<h3 class="question-h3">%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'Question'))=%%</h3>
<div id="" class="question">
%%[
SET #answerOptions = BuildRowsetFromString(FIELD(ROW(#quizData,#qNum),'QuestionAnswerOptions'),'|')
SET #answerCount = RowCount(#answerOptions)
FOR #aNum = 1 to #answerCount DO
SET #answer = FIELD(ROW(#answerOptions,#aNum),1)
]%%
<div id="answerOptions">
<input value="%%=TreatAsContent(#answer)=%%" class="button-submit btnAnswer" name="Q%%=V(#qNum)=%%A%%=V(#aNum)=%%" type="button">
</div>
%%[
NEXT #aNum
]%%
<!-- BEGIN HIDE CRCT ANSWER FOR JS VALIDATION -->
<input name="crctAnswer" value="%%=V(FIELD(ROW(#quizData,#qNum),'questionCrctAnswerValue'))=%%" type="hidden">
</div>
<!-- END HIDE CRCT ANSWER FOR JS VALIDATION -->
<!-- HIDE/SHOW BASED ON SELECTION -->
<div id="" class="answer">
<div class="answer-title" style="display:none;"> <img class="icon" src="http://image.em.pge.com/lib/fe8c13727666037a72/m/6/general_cancel.png">
<h4 class="answer-h4-incorrect" style="display:none;">You are incorrect.</h4> </div>
<div class="answer-title" style="display:none;"> <img class="icon" src="http://image.em.pge.com/lib/fe8c13727666037a72/m/6/general_check.png">
<h4 class="answer-h4-correct" style="display:none;">You are correct!</h4> </div>
<div class="answer-explaination" style="display:none;">
<p class="answer-explaination" style="display:none;"><strong>The correct answer.</strong>%%=TreatAsContent(FIELD(ROW(#quizData,#qNum),'QuestionCrctAnswerText'))=%%</p>
</div>
</div>
</div>
Try using the jQuery button click handler
$(".btnAnswer").click( function() {
$(this).attr('name');
// or
this.name;
});
I guess you'd use Jquery like this:
$(".btnAnswer").click(function() {
// jQuery way
var btnValue = $(this).val();
var btnName = $(this).attr("name");
// Javascript way
var btnValue = this.value;
var btnName = this.name;
var btnQuestion = btnName.substring(0, btnName.indexOf('A'));
btnQuestion = btnQuestion.substring(btnQuestion.indexOf('Q') + 1);
var btnAnswer = btnName.substring(btnName.indexOf('A') + 1);
updateScore(btnQuestion, btnAnswer);
});

Javascript functions overlapping

I have two functions that happen when a link is clicked, a box drops down.
<div class='buttons'><a href = '#' onclick = "return false" onmousedown = "javascript:toggleInteractlogin('login')"class='regular' name='save'> Log In </div></a>
<div class='buttons'><a href = '#' onclick = "return false" onmousedown = "javascript:toggleInteractlogin('register')" class='regular' name='save'> Register</div></a><br><br>
<div class = "Interactlogin" id = "login"> Login</div>
<div class = "Interactlogin" id = "register"> Logina</div>
When login is clicked, the log in box slides down, but then when the register box is clicked, the login box slides further to accommodate for the register box whereas i would like only one box to be shown at a time.
Any help is appreciated.
function toggleInteractlogin(x)
{
if($('#' + x).is(":hidden"))
{
$('#'+x).slideDown(200);
}
else
{
$('#'+x).hide();
}
$('Interactlogin').hide();
}
I have updated the solution in LIVE DEMO - JSFiddler
HTML
<div class='buttons'>
<a id="btnlogin" href= '#' class='login' name='save'>Log In </a>
</div>
<div class='buttons'>
<a id="btnregister" href='#' class='regular' name='save'>Register</a>
</div><br><br>
<div class="Interactlogin" id="login" style="display:none">Login</div>
<div class="Interactlogin" id="register" style="display:none">Logina</div>​
JS
$('#btnlogin').click(function(){
$('#login').show();
$('#register').hide();
});
$('#btnregister').click(function(){
$('#login').hide();
$('#register').show();
});
​
make sure you slide up the register box first when login button is clicked, similarly make sure you slide up the login button first when when register button is clicked
so for loginn button click
1 slide up the register box
2 then slide down the login box
similarly for register
1 slide up the login box
2 then slide down the register box.
try specifying different ids to login & register button
function toggleInteractlogin(x)
{
if(x=='register')
{
$('#login').hide();
$('#register').show();
}
else
{
$('#register').hide();
$('#login').show();
}
}
for show/hide you can specify different effect as well like fadein/fadeout
You can simplify this a bit using this revised markup:
<div class='buttons'><a href='#' class='login'>Log In</a></div>
<div class='buttons'><a href='#' class='register'>Register</a></div>
<br><br>
<div class = "Interactlogin" id = "login">Login</div>
<div class = "Interactlogin" id = "register">Logina</div>
$('.login,.register').mousedown(function() {
$('.Interactlogin').hide();//hide them all initially
var myType = $(this).attr('class');//assumption this is the only class
$('#' + myType).slideDown(200);
});
I assume this CSS to hide initially:(yours may differ)
.Interactlogin{display:none;}

Categories

Resources