See if there is a form inside a div - javascript

I have a div with an id like: comment-box-5 and I want to see using javascript if there is a form inside of it if so remove it if not add it (so it toggles when I call the function). I wrote this piece of code to try to do this:
function reply(id){
console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id)));
if (document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))) {
var form = replyFn(id);
document.getElementById('comment-id-' + id).appendChild(form);
} else {
//for toogle effect
document.getElementById('comment-id-' + id).removeChild(document.getElementById("form-" + id));
}
}
And I tried executing it but console.log(document.getElementById('comment-id-' + id).innerHTML.indexOf(document.getElementById('form-' + id))); prints -1 even if there is a form inside.
What am I doing wrong? how can I actually see if there is a form in the div?

You could change your condition to :
if ( document.querySelector('#comment-id-' + id +'>#form-' + id) ) {
//Your if logic
}else{
//Your else logic
}
Snippet :
var id = 1;
if (document.querySelector('#comment-id-' + id + '>#form-' + id)) {
console.log('Remove form');
} else {
console.log('Add form');
}
<div id="comment-id-1">
<form id="form-1"></form>
</div>

Try using contains on the div without innerHTML like below, I changed the code from yours a bit to do the example but it should work for yours as well.
console.log(document.getElementById('comment-id-1').contains(document.getElementById('form-id-1')));
<div id="comment-id-1"><form id="form-id-1"></form></div>

Related

javascript function to prevent user from changing the value of a specific column

Hope you're doing well
I'm new to JavaScript and I need your help to complete the code below.
I've written a JS code as you can see below :
$("#input_KindCode").change(function () {
if ($(this).val() == 1) {
RunSql("Select DateKey From ProjectExecution.Contractinfo WHERE PlanCode = " + $("#input_PlanCode").val() + " AND ProjectCode = '" + $("#input_ProjectCode").val() + "' AND ContractCode = '" + $("#input_ContractCode").val() + "' AND KindCode = 1 ", function (data) {
if (data.length > 0) {
$("#input_DateKey").val(data[0].DateKey);
/////// THIS PART///////
} else {
$("#input_DateKey").val('');
EnableCol("DateKey");
}
});
}
else {
$("#input_DateKey")[0].value = '';
EnableCol("DateKey");
};});
In the 'RunSql' part of the code , I'm checking whether the 'datekey' column has value if true the value will show up in the field otherwise the user must enter the value for the column.
The problem is I want to add something to the code . I want to show the value if it exists AND I want to disable the column so that the user can not change the value . I can not use the function 'disable column' cause it does not work in my case are there any other functions ??
so I want a function to prevent user from changing the value of the column if it is being shown on the field. the function must be written in the 'This part' part of the code
Thanks in advance
You can disable this input field using jquery. To perform this you need to add one line.
Code:
if (data.length > 0) {
$("#input_DateKey").val(data[0].DateKey);
$("#input_DateKey").prop('disabled',true);
} else {
$("#input_DateKey").val('');
$("#input_DateKey").prop('disabled',false);
EnableCol("DateKey");
}

Textarea value remain the same after submitting a form

My previous problem has been fixed, now I need to ask how to keep a textarea from resetting its input after a form is submitted. Here is the jsFiddle: http://jsfiddle.net/rz4pnumy/
Should I change the form in the HTML?
<form id="form1" method="GET">
(the form does not go into a php file or anything else, i'm using it to submit the textarea input and use the variables I made using jQuery to make a paragraph on the same page)
or something in the JS?
$(document).ready( function () {
$('#form1').on('submit', function (event) {
// If the form validation returns false, block the form from submitting by
// preventing the event's default behaviour from executing.
if (!validate()) {
event.preventDefault();
}
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
var verb1 = $('#verb1').val();
var edibleobject = $('#edible-object').val();
var monster1 = $('#monster1').val();
var adjective3 = $('#adjective3').val();
var monster2 = $('#monster2').val();
var verb2 = $('#verb2').val();
$('body').append(
'<div id="para">' +
'<p>Rain was still lashing the windows, which were now ' + adjective1 +', but inside all looked bright and cheerful. ' +
'The firelight glowed over the countless ' + adjective2 + '' + pluralnoun + ' where people sat ' + verb1 + ', talking, ' +
'doing homework or, in the case of Fred and George Weasley, trying to find out what would happen if you fed a ' + edibleobject +' to a ' + monster1 + '.' +
'Fred had "rescued" the ' + adjective3 + ', fire-dwelling ' + monster2 + ' from a Care of Magical Creatures class and it was now ' + verb2 + ' gently ' +
'on a table surrounded by a knot of curious people. </p>' +
'</div>'
);
}
});
function validate() {
var success = true;
$('.input').each(function(i, item) {
if ($(item).val() === "")
{
console.log("Missing textarea input");
success = false;
$(item).attr("style","border:1px solid red;");
//note it will overwrite your element style in all Input class
}
else
{
$(item).removeAttr('style')
// to remove border
}
});
return success;
}
});
The contents get emptied after pressing submit and I only see the completed paragraph for a split second.
You need to prevent the default event handler from executing whether validate passes or not, so you need to remove the if statement around the event.preventDefault() call. The preventDefault is the function that is keeping the from from submitting and re-loading your page.
Also, your Fiddle was not set to jQuery (it was set to no-library) so that may have also been causing you issues during your testing.
Edited for example of what I'm talking about:
$('#form1').on('submit', function (event) {
// block the form from submitting by
// preventing the event's default behaviour from executing.
event.preventDefault();
if(validate()) {
var adjective1 = $('#adjective1').val();
var adjective2 = $('#adjective2').val();
var pluralnoun = $('#plural-noun').val();
... etc ...
I would use php and set a variable to the GET value of the textarea and set the value of the textarea to that variable

If div contains a span with a class based on parameter

Im trying to create a simple function that create span's with an class that equals whatever is piped into the function. These spans fill inside a parent div. I also want to ensure that once a span has been added that another span is not add with that id/class, unless my multiSearchEnabled boolean is true.
Here is some code i've
function createBadge(badge_type) {
var badge_parent_div = $("#badge-column-div");
var badge = "<span class='badge-text " + badge_type + "'>" + badge_type + "</span>";
if (!$(badge_parent_div.find("span").hasClass(badge_type))) {
badge_parent_div.append(badge);
} else {
if (multiSearchEnabled) {
badge_parent_div.append(badge); // Add another Badge, since search contains multiples
}
}
}
However this doesnt seem to work, this function will be ran onKeyUp therefore is why i need to detect if the span already exists for this type, so i dont duplicate it.
Updated based on suggestions
function createBadge(badge_type) {
var badge = "<span class='" + badge_type + "'>" + badge_type + "</span>";
var bHasBadge = $("#badge-column-div").has('.' + badge_type);
if (bHasBadge == false || (bHasBadge && multiSearchEnabled == true))
{
// add it
$("#badge-column-div").append(badge);
}
}
However with the following code, nothing ever get's added. I need it add a badge initially, then only if the multiSearchEnabled boolean is true to add more than one.
has() checks for child controls matching a selector.
function createBadge(sBadgeType)
{
var oBadgeParent = $("#badge-column-div");
var bHasBadge = oBadgeParent.has("span." + sBadgeType)
if (bHasBadge == false || bMultiSearchEnabled)
oBadgeParent.append
(
$("<span class='badge-text " +sBadgeType+ "'>" +sBadgeType+ "</span>")
);
}

JQuery functions declaration and reusing it

I've got the following jQuery code
$('#rta_ad_yes').click(function(){
$('#rta_ad_pref, #rta_ad_psn').prop('disabled', false);
$('#div_ad_pref, #div_ad_psn').addClass('has-warning');
});
$('#rta_fp_yes').click(function(){
$('#rta_ad_fpref, #rta_ad_fpsn').prop('disabled', true);
$('#div_ad_fpref, #div_ad_fpsn').addClass('has-warning');
});
If you look at the above code it seems i'm doing same coding to achieve the same result.. $('#rta_ad_yes') and $('#rta_fp_yes') in two different pages
sorry to not mentioning my question question how can i declare and call that function provide parameters rather than typing the whole thing again and again.. i dont know how to declare function and reuse it in jquery not very good at jquery
you can try the following code.
function isEmpty (test_obj, element){
if(!test_obj.val().length > 0){
element.addClass('has-warning');
return false;
}else{
element.removeClass('has-warning');
return true;
}
};
and reuse that like below
var x = isEmpty($('#rta_cl_fn'), $('#div_cl_fn'));
hope that helped
Try
.split()
$('#rta_ad_yes', '#rta_fp_yes').click(function () {
var id = (this.id.split('_')[1] == 'fp')? 'f' : '';//get ad or fp from id
//if it's `fp` than add `f` if not than empty string .
$('#rta_ad_' + id + 'pref, #rta_ad_' + id + 'psn').prop('disabled', function(){
return id.length;//return false if 0 and for 1 return true .
}); //make id out of it
$('#div_ad_' + id + 'pref, #div_ad_' + id + 'psn').addClass('has-warning');
});
I believe you want to abstract that in a function?
var disableAndWarn = function (config) {
$("#" + config.id1 + ', ' + "#" + config.id2).attr('disabled', 'disabled');
$("#" + config.id3 + ', ' + "#" + config.id4).addClass('has-warning');
}
Here is a FIDDLE
Edit: Changed your .prop('disabled', true) into .attr('disabled', 'disabled') since I believe that's what you intended.

Getting ALL children from all levels

im about to develop a Formvalidator. I use a global Function which i call before every form-submit, i also give the form ID for accessing the inputs. so the function looks like this:
function FormValidation(formId)
{
var validated = true;
$("#" + formId ).each(function ()
{
var message="";
if ($(this).attr("data-validation-required") == "true" && $(this).val() == "") {
message += "-This field is required<br/>";
validated = false;
if (message != "")
$(this).after('<div class="popover fade bottom validation-error in" style="position:relative;display: block; margin-top:0px;"><div class="arrow" style="left:10% !important;"></div><div class="popover-content" style="color:#c0392b;">' + message + '</div></div>');
}
return validated; //true or false
}
so the problem is, that this each loop i wrote, is not accessing ALL children which are within the given "form" (by formId). Its accessing only the FIRST level children.
Here's some HTML example code:
<form id="myform">
<input type="text" data-validation-required="true"/> <-- will be accessed -->
<div class="SomeDivClass">
<input type="text" data-validation-required="true"/> <-- will NOT be accessed because 2nd level -->
</div>
</form>
<script>
$("#myform").submit(function(){
if(!FormValidation("myform"))
return false;
});
</script>
There are few issues in the given code
function FormValidation(formId) {
var validated = true;
//use descendant selector to find all required fields
$("#" + formId + ' [data-validation-required="true"]').each(function () {
//check whether the value is empty, if so mark as invalid
if ($(this).val() == "") {
var message = "-This field is required<br/>";
validated = false;
$(this).after('<div class="popover fade bottom validation-error in" style="position:relative;display: block; margin-top:0px;"><div class="arrow" style="left:10% !important;"></div><div class="popover-content" style="color:#c0392b;">' + message + '</div></div>');
} else {
//remove the validation of it is again become valid
$(this).next('.validation-error').remove()
}
//don't return the validated from the each loop since returning false here will cause the each loop to stop further iterations
})
return validated; //true or false
}
$("#myform").submit(function () {
if (!FormValidation("myform")) {
return false;
}
});
Demo: Fiddle
You could get all elements with data-validation-required via $('#' + formId +' [data-validation-required!=""]')
The jQuery API for traversing the DOM is incredibly well documented. To get all descendants of an element, you'd use .find(), along with a selector that didn't exclude anything — * — so your code would end up as follows:
$("#" + formId ).find( '*' ).each(function (){
But seeing as you're already creating a CSS selector to select the form, you may as well simply extend that selector:
$("#" + formId + " *").each(function (){
Your current form isn't even iterating the children — it's iterating over each form, and there's only one.

Categories

Resources