Code Bug Fix: Is there a way for a React Component to be notified when the element it is attached to is deleted outside of React

Original Source Link

Our application consists of lots of legacy code written using jQuery and some newer React components.
We have mostly been able to handle separating concerns between the two, most of our code is one or the other – but occasionally we have React Components within JQuery Components.

In most cases:
JQuery creates a Div, the Div Element is passed to a ReactDOM.render and control for that div is controlled by react.
Then before JQuery destroys the Div it will call ReactDOM.unmountComponentAtNode to do the tear down.

However we have some JQuery code that is being removed in a way that is not trivial to detect that some of it is actually React, creating a component memory leak.

The correct fix for us it to solve the tear down, so that the unMounts are always called correctly, but there are engineering risks in this as the legacy code is not the cleanest and the risk of introduction of new bugs is high.

My question is whether there is a way that React Components can spot that they have become orphaned. ComponentWillUnmount is not the answer (as it does not get called in this scenario).

You could use a mutation observer on the component’s parent, but I’d be surprised if it were really necessary.

Basically, you’d:

  • Use a ref on the top-level element returned by your component in render.
  • In componentDidMount, use current from the ref to find the parentNode and set up a mutation observer on it, watching for childList changes.
  • In the observer callback, look for a mutation record where the ref’s current node in the list of removed nodes.
    • If so, do any cleanup that you have to do.

Live Example:

class Example extends React.Component {
    constructor(props) {
        super(props);
        this.ref = React.createRef(null);
        this.cleanedUp = false;
    }
    
    componentDidMount() {
        this.cleanedUp = false;
        // assert(this.ref.current !== null);
        if (this.observer) {
            this.observer.disconnect();
        }
        this.observer = new MutationObserver(records => {
            if (this.cleanedUp) {
                return;
            }
            for (const record of records) {
                for (const node of record.removedNodes) {
                    if (node === this.ref.current) {
                        this.cleanup();
                        return;
                    }
                }
            }
        });
        this.observer.observe(this.ref.current.parentElement, {
            childList: true,
            subtree: true
        });
    }
    
    componentWillUnmount() {
        this.cleanup();
    }

    cleanup() {
        console.log("Clean up here");
        this.observer.disconnect();
        this.observer = null;
        this.cleanedUp = true;
    }
    
    render() {
        return <div ref={this.ref}>This is the component's top level element</div>;
    }
}

const root = document.getElementById("root");
ReactDOM.render(<Example/>, root);

// Outside React...
setTimeout(() => {
    root.innerHTML = ""; // Bludgeon its contents
}, 1000);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

You might have to watch from further up in the document tree than just the component’s immediate parent, but that’s the general idea…


Note: Using for-of on the removedNodes as I have above relies on the browser making NodeList iterable. Modern browsers do, but slightly older ones may not. My answer here talks about how to make them iterable (assuming the iteration protocol is supported by the browser’s JavaScript engine), or you might use forEach instead (also discussed there).

Tagged : /

Code Bug Fix: Is there a more efficient way to replace multiple strings in a html?

Original Source Link

first of all please excuse my bad title. Don’t know how to name it.
This is a student project. My task is to explore/examine many, fairly large, texts in a web app.
But this is not important, that’s anyway the way how it needs to be done.
The strings that needs to be replaced are stored in a json file. I’m iterating throw the file with

$.each(stringList, function(index, value) {
var isInContent = $('#myContent').text().indexOf(index) > -1;
if (isInContent) {... replaceString(index); ...}
}

And to replace the string I use

$('#myContent :not(script)').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
  return this.nodeValue.replace(index, myNewString);
});

It works as it should. But it’s a bit slow. I think because it’s loading for every replace the $(‘#content’) and writes the whole $(‘#content’) after the replace back to the html.
Is there a more efficient way to do it?

Thank you

Tagged : / / / /

Code Bug Fix: any no. of alphanumeric value by mask input validation

Original Source Link

How I can add multiple alphanumeric characters. In regular expression we use [a-zA-z0-9 ]+, + signifies you can add atleast one alphanumeric. So, how I can achieve this through mask i.e. adding multiple alphanumeric characters.

I have tried the following:

jQuery('.alphanumeric-field').mask('A')

$('.Address, .APT').mask('Z', {
    translation: {
      'Z': { pattern: "^[a-zA-Z0-9_ ]*$", optional: true, recursive: true}
    },
    maxlength: false
  });

Tagged : /

Code Bug Fix: How to get all inputs from a form – not working from selector

Original Source Link

I have the following html:

×

                    <!-- Modal Body -->
                    <div class="modal-body">
                      <form id="modal_revenue_form" role="form" method="POST" action="">
                        <div id="modal_revenue_formgroup_year" class="form-group">
                            <label class="control-label" for="modal_revenue_form_year">Year</label>
                            <select class="form-control select2" style="width: 100%;" id="modal_revenue_form_year" data-placeholder="Select a year">
                              <option value="" ></option>
                                                                <option value="2015" >
                                2015
                              </option>
                                                                <option value="2016" >
                                2016
                              </option>
                                                                <option value="2017" >
                                2017
                              </option>
                                                                <option value="2018" >
                                2018
                              </option>
                                                                <option value="2019" >
                                2019
                              </option>
                                                                <option value="2020"  selected >
                                2020
                              </option>
                                                                <option value="2021" >
                                2021
                              </option>
                                                                <option value="2022" >
                                2022
                              </option>
                                                                <option value="2023" >
                                2023
                              </option>
                                                                <option value="2024" >
                                2024
                              </option>
                                                                <option value="2025" >
                                2025
                              </option>
                                                              </select>
                            <span id="modal_revenue_form_year_error" class="help-block"></span>
                        </div>
                        <div id="modal_revenue_formgroup_fpc" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_fpc">FPC</label>
                            <input type="text" id="modal_revenue_form_fpc" class="form-control" placeholder="FPC"></input>
                            <span id="modal_revenue_form_fpc_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_jan" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_jan">jan</label>
                            <input type="text" id="modal_revenue_form_jan" class="form-control" placeholder="jan"></input>
                            <span id="modal_revenue_form_jan_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_feb" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_feb">feb</label>
                            <input type="text" id="modal_revenue_form_feb" class="form-control" placeholder="feb"></input>
                            <span id="modal_revenue_form_feb_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_mar" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_mar">mar</label>
                            <input type="text" id="modal_revenue_form_mar" class="form-control" placeholder="mar"></input>
                            <span id="modal_revenue_form_mar_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_apr" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_apr">apr</label>
                            <input type="text" id="modal_revenue_form_apr" class="form-control" placeholder="apr"></input>
                            <span id="modal_revenue_form_apr_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_may" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_may">may</label>
                            <input type="text" id="modal_revenue_form_may" class="form-control" placeholder="may"></input>
                            <span id="modal_revenue_form_may_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_jun" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_jun">jun</label>
                            <input type="text" id="modal_revenue_form_jun" class="form-control" placeholder="jun"></input>
                            <span id="modal_revenue_form_jun_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_jul" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_jul">jul</label>
                            <input type="text" id="modal_revenue_form_jul" class="form-control" placeholder="jul"></input>
                            <span id="modal_revenue_form_jul_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_aug" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_aug">aug</label>
                            <input type="text" id="modal_revenue_form_aug" class="form-control" placeholder="aug"></input>
                            <span id="modal_revenue_form_aug_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_sep" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_sep">sep</label>
                            <input type="text" id="modal_revenue_form_sep" class="form-control" placeholder="sep"></input>
                            <span id="modal_revenue_form_sep_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_oct" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_oct">oct</label>
                            <input type="text" id="modal_revenue_form_oct" class="form-control" placeholder="oct"></input>
                            <span id="modal_revenue_form_oct_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_nov" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_nov">nov</label>
                            <input type="text" id="modal_revenue_form_nov" class="form-control" placeholder="nov"></input>
                            <span id="modal_revenue_form_nov_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_dec" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_dec">dec</label>
                            <input type="text" id="modal_revenue_form_dec" class="form-control" placeholder="dec"></input>
                            <span id="modal_revenue_form_dec_error" class="help-block"></span>
                        </div>

                        <div class="form-group">
                            <div id="modal_revenue_form_hidden"></div>
                        </div>
                      </form>
                    </div>

                    <!-- Modal Footer -->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" id="modal_revenue_create_update_button" class="btn btn-success"></button>
                    </div>
                  </div>
              </div>
          </div>
          <!-- Modal -->

and the following jquery to set all inputs to a certain value:

$(document).ready(function() {
    function modal_revenue_form_clean(title) {
          $('#modal_revenue_title').text(title+' Revenue');
          $('#modal_revenue_create_update_button').text(title);
          $('#modal_revenue_form_hidden').empty();

          // Set date to today's year
          var d = new Date();
          var year = d.getFullYear()
          $('select#modal_revenue_form_year').val(year);
          $('select#modal_revenue_form_year').select2().trigger('change');

          $('#modal_revenue_form_fpc').val(0);

          // Clean all input <---- I don't get this alert below
          $("form#modal_revenue_form input").each(function(){
            alert('ok');
            $(this).val('dfgsdfgdf');
          });
          // Set all months value to 0
          @foreach(config('select.available_months') as $key => $month)
            $('#modal_revenue_form_{{ $month }}').val(0);
          @endforeach

          //modal_revenue_form_error_clean();
        }
});

This jquery code is in a function and when I call it, nothing happens, I don’t get alerts. I ave checked on other website and it seems this is the way to select all inputs in a specific form.

Why is it not working?

You need wrap your code inside document ready as

$(document).ready(function(){
      $("form#modal_revenue_form input").each(function(){
        //alert('ok');
        $(this).val('dfgsdfgdf');
      });
});   

$(document).ready(function(){
      $("form#modal_revenue_form input").each(function(){
        //alert('ok');
        $(this).val('dfgsdfgdf');
      });
});   
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
!-- Modal Body -->
                    <div class="modal-body">
                      <form id="modal_revenue_form" role="form" method="POST" action="">
                        <div id="modal_revenue_formgroup_year" class="form-group">
                            <label class="control-label" for="modal_revenue_form_year">Year</label>
                            <select class="form-control select2" style="width: 100%;" id="modal_revenue_form_year" data-placeholder="Select a year">
                              <option value="" ></option>
                                                                <option value="2015" >
                                2015
                              </option>
                                                                <option value="2016" >
                                2016
                              </option>
                                                                <option value="2017" >
                                2017
                              </option>
                                                                <option value="2018" >
                                2018
                              </option>
                                                                <option value="2019" >
                                2019
                              </option>
                                                                <option value="2020"  selected >
                                2020
                              </option>
                                                                <option value="2021" >
                                2021
                              </option>
                                                                <option value="2022" >
                                2022
                              </option>
                                                                <option value="2023" >
                                2023
                              </option>
                                                                <option value="2024" >
                                2024
                              </option>
                                                                <option value="2025" >
                                2025
                              </option>
                                                              </select>
                            <span id="modal_revenue_form_year_error" class="help-block"></span>
                        </div>
                        <div id="modal_revenue_formgroup_fpc" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_fpc">FPC</label>
                            <input type="text" id="modal_revenue_form_fpc" class="form-control" placeholder="FPC"></input>
                            <span id="modal_revenue_form_fpc_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_jan" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_jan">jan</label>
                            <input type="text" id="modal_revenue_form_jan" class="form-control" placeholder="jan"></input>
                            <span id="modal_revenue_form_jan_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_feb" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_feb">feb</label>
                            <input type="text" id="modal_revenue_form_feb" class="form-control" placeholder="feb"></input>
                            <span id="modal_revenue_form_feb_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_mar" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_mar">mar</label>
                            <input type="text" id="modal_revenue_form_mar" class="form-control" placeholder="mar"></input>
                            <span id="modal_revenue_form_mar_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_apr" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_apr">apr</label>
                            <input type="text" id="modal_revenue_form_apr" class="form-control" placeholder="apr"></input>
                            <span id="modal_revenue_form_apr_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_may" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_may">may</label>
                            <input type="text" id="modal_revenue_form_may" class="form-control" placeholder="may"></input>
                            <span id="modal_revenue_form_may_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_jun" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_jun">jun</label>
                            <input type="text" id="modal_revenue_form_jun" class="form-control" placeholder="jun"></input>
                            <span id="modal_revenue_form_jun_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_jul" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_jul">jul</label>
                            <input type="text" id="modal_revenue_form_jul" class="form-control" placeholder="jul"></input>
                            <span id="modal_revenue_form_jul_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_aug" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_aug">aug</label>
                            <input type="text" id="modal_revenue_form_aug" class="form-control" placeholder="aug"></input>
                            <span id="modal_revenue_form_aug_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_sep" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_sep">sep</label>
                            <input type="text" id="modal_revenue_form_sep" class="form-control" placeholder="sep"></input>
                            <span id="modal_revenue_form_sep_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_oct" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_oct">oct</label>
                            <input type="text" id="modal_revenue_form_oct" class="form-control" placeholder="oct"></input>
                            <span id="modal_revenue_form_oct_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_nov" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_nov">nov</label>
                            <input type="text" id="modal_revenue_form_nov" class="form-control" placeholder="nov"></input>
                            <span id="modal_revenue_form_nov_error" class="help-block"></span>
                        </div>
                                                    <div id="modal_revenue_formgroup_dec" class="form-group">
                            <label  class="control-label" for="modal_revenue_form_dec">dec</label>
                            <input type="text" id="modal_revenue_form_dec" class="form-control" placeholder="dec"></input>
                            <span id="modal_revenue_form_dec_error" class="help-block"></span>
                        </div>

                        <div class="form-group">
                            <div id="modal_revenue_form_hidden"></div>
                        </div>
                      </form>
                    </div>

                    <!-- Modal Footer -->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" id="modal_revenue_create_update_button" class="btn btn-success"></button>
                    </div>
                  </div>
              </div>
          </div>
          <!-- Modal -->
Tagged :

Code Bug Fix: How can i hide the back button in my site when there is no back URL available using JS / jQuery?

Original Source Link

I’ve back button in my site and i want to hide, if there is no back URL available(i.e from my site). i used history of JS to check history.length and go() for back to previous URL. To check back URL is from my site or not i used

var prev_url = document.referrer;
if(prev_url.indexOf(window.location.origin) === -1){
  // hide back button
}

which is working fine but document.referrer is changed if i clicked other link in my site and if i go back to previous page then the document.referrer is referring forwarded link which i don’t want. i want current opened page previous URL not referrer URL. if anyone have any other option than document.referrer this let me know plz.

If have any other solution.. will be helpful.

Thanks.

Tagged : /

Server Bug Fix: PHP+AJAX with MySQL – Query every 2 seconds, too many in TIME_WAIT

Original Source Link

I have a basic HTML file, using jQuery’s ajax, that is connecting to my polling.php script every 2 seconds.

The polling.php simply connections to mysql, checks for ID’s newer than my hidden, stored current ID, and then echo’s if there is anything new. Since the javascript is connecting every 2 seconds, I am getting thousands of connections in TIME_WAIT, just for my client. This is because my script is re-connecting to MySQL over and over again. I have tried mysql_pconnect but it didn’t help any.

Is there any way I can get PHP to open 1 connection, and continue to query using it? Instead of reconnecting every single time and making all these TIME_WAIT connections. Unsure what to do here to make this work properly.

No, it is not possible. There is no way for php to open only one connection, because every request to HTTP server is passed to worker process, which execute php script (and create new connection).

If your MySQL and HTTP server are running on same server, you could use unix socket connection instead of TCP connection.

You colud adjust net.ipv4.netfilter.ip_conntrack_tcp_timeout_time_wait kernel parameter, to reduce number of connections in TIME_WAIT state.

You can connect to MySQL via unix domain sockets instead, given PHP server and MySQL server are on the same server. Here are some hints how to switch to domain sockets:

MacPorts, MySQL, PHP5 and that socket thing ..

If you have separate servers you may want to find out more about connection pooling. The most simplistic approach to get started seems to be using mysql_pconnect instead of mysql_connect. (p for persistent)

Tagged : / / /

Code Bug Fix: how to change a selections options based on another select option selected?

Original Source Link

here is my html.

<select id="type">
<option value="item1">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
</select>

<select id="size">
<option value="">-- select one -- </option>
</select>

here is the jquery i tried but was unsuccessful.

$(document).ready(function() {

if( $("#type").val("item1"))
{
  $("#size").html("<option value='test'>test</option><option value="test2">test2</option>);
}
elseif( $("#type").val("item2"))
{
   $("#size").html("<option value='anothertest1'>anothertest1</option>");
}

});

basically what i’m trying to do is if an option is selected in #type then the size select is populated with options associated to it. how can i do this?

thanks

Here is an example of what you are trying to do => fiddle

$(document).ready(function () {
    $("#type").change(function () {
        var val = $(this).val();
        if (val == "item1") {
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");
        } else if (val == "item2") {
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");
        } else if (val == "item3") {
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");
        } else if (val == "item0") {
            $("#size").html("<option value=''>--select one--</option>");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="type">
    <option value="item0">--Select an Item--</option>
    <option value="item1">item1</option>
    <option value="item2">item2</option>
    <option value="item3">item3</option>
</select>

<select id="size">
    <option value="">-- select one -- </option>
</select>

you can use data-tag in html5 and do this using this code:

<script>
	$('#mainCat').on('change', function() {
		var selected = $(this).val();
		$("#expertCat option").each(function(item){
			console.log(selected) ;  
			var element =  $(this) ; 
			console.log(element.data("tag")) ; 
			if (element.data("tag") != selected){
				element.hide() ; 
			}else{
				element.show();
			}
		}) ; 
		
		$("#expertCat").val($("#expertCat option:visible:first").val());
		
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<select id="mainCat">
			<option value = '1'>navid</option>
			<option value = '2'>javad</option>
			<option value = '3'>mamal</option>
		</select>
		
		<select id="expertCat">
			<option  value = '1' data-tag='2'>UI</option>
			<option  value = '2' data-tag='2'>Java Android</option>
			<option  value = '3' data-tag='1'>Web</option>
			<option  value = '3' data-tag='1'>Server</option>
			<option  value = '3' data-tag='3'>Back End</option>
			<option  value = '3' data-tag='3'>.net</option>
		</select>

Here is my simple solution using Jquery filters.

$('#publisher').on('change', function(e) {
   let selector = $(this).val();
   $("#site > option").hide();
   $("#site > option").filter(function(){return $(this).data('pub') == selector}).show();
});

JSFIDDLE

as a complementary answer to @Navid_pdp11, which will enable to select the first visible item and work on document load as well.
put the following below your body tag

<script>
$('#mainCat').on('change', function() {
    let selected = $(this).val();
    $("#expertCat option").each(function(){
        let element =  $(this) ;
        if (element.data("tag") != selected){
            element.removeClass('visible');
            element.addClass('hidden');
            element.hide() ;
        }else{
            element.removeClass('hidden');
            element.addClass('visible');
            element.show();
        }
    });
    let expertCat = $('#expertCat');
    expertCat.prop('selectedIndex',expertCat.find("option.visible:eq(0)").index());
}).triggerHandler('change');
</script>

You can use switch case like this:

$(document).ready(function () {
  $("#type").change(function () {
     switch($(this).val()) {
        case 'item1':
            $("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");
            break;
        case 'item2':
            $("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");
            break;
        case 'item3':
            $("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");
            break;
        default:
            $("#size").html("<option value=''>--select one--</option>");
     }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="type">
    <option value="item0">--Select an Item--</option>
    <option value="item1">item1</option>
    <option value="item2">item2</option>
    <option value="item3">item3</option>
</select>

<select id="size">
    <option value="">-- select one -- </option>
</select>

Your if statement is setting the value. You want to compare it by doing this

if ($("#type").val() == "item1") {
 ...
}

daLizard is right though. You want an event handler. document.ready runs only once, when the page DOM is ready to be used.

I don’t quote understand what you are trying to achieve, but you need an event listener. Something like:

$('#type').change(function() {
   alert('Value changed to ' + $(this).attr('value'));
});

This will give you the value of the selected option tag.

Tagged :

Server Bug Fix: Apache + Flask + WSGI – Static Files from JS?

Original Source Link

Having a lot of trouble getting this filepath to load in my js code.
Relevant snippets:

  1. etc/apache2/sites-enabled/canact-le-ssl.conf:
# Give an alias to to start your website url with
 WSGIScriptAlias / /home/c_site/mysite/canact/canact_app.wsgi
 <Directory /home/c_site/mysite/canact/>
        # set permissions as per apache2.conf file
        Options FollowSymLinks
        AllowOverride None
        Require all granted
 </Directory>
  1. /mysite/canact/canact_app.wsgi:
#! /usr/bin/python3.6
import logging
import sys
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0, '/home/c_site/mysite/canact/')
from canact_app import app as application
  1. /mysite/canact/static/js/cards.js
$(".cause_text").load("/static/assets/content/file.txt");

Console & Network debug in browser show:

jquery.min.js:2 GET https://www.xxxx.org/static/assets/content/file.txt 404 (NOT FOUND)

My HTML Templates are still able to access static content by using {{ url_for }}

Tagged : / / /

Code Bug Fix: How to make a nested for loop inside of string in javascript

Original Source Link

I have an AJAX call return with a lot of data.

Thus, I want to update some html contents. I need two nested for loop to append to html elements.

  • I need first for loop to append all comments to HTML div.
  • The other for loop to append images for each comment.

However, I have an error around the second loop closing parentheses and the for loop closing curly bracket.

Please Note: second loop there are two variables “i” and “j”. I need to fetch all images for each comment

Here is the code:

// post comments box
var comment_box_start = $('#comment-box-start').html(''); // reset comments box 

for(var i= 0; i< json.comments.length; i++){

      comment_box_start.append('<div class="comment-text">'+
                               '<p id="'+json.comments[0].comment_id+'" class="comment-text-filler float-right">'+
                                 json.comments[0].comment_content+
                                '</p>'+
                                '</div>'+

                          '<div id="comment-imgs" class="comment-imgs flex-wrap">'+



                            '<div class="flex flex-row flex-wrap custom-size float-right">'+ 
                              // place condition if the sub_category has a theme 
                              '<div id="post-carousel-item">' +
                                for(var j = 0; j < json.images.length; j++) {
                                 '<a href="../../../../media/'+json.comments[i].comment_images[j].images+'" data-imagelightbox="demo" data-ilb2-caption="Caption 1">'+
                                  '<img src="../../../../media/'+json.comments[i].comment_images[j].images+ '" alt="..."/>'+
                                  '</a>'+
                                  }+
                              '</div>'+
                              // place empty condition if the sub_category hoes not has a theme 
                              '<div></div>'+
                              // close if condition 


                            '</div>'+                             

                        '</div>'+



                        '<div class="d-flex ">'+
                              '<div class="d-flex bd-highlight clearfix justify-content-between m-2">'+

                                    '<div class="order-2 align-self-center mr-auto p-1 ml-2 toltip-color">'+
                                        '<a  href="" data-toggle="tooltip" data-placement="top" title="">'+
                                          //flag icons 
                                          '<i class="fas fa-flag comment-report-flag" id="comment-report-flag">'+
                                           0
                                          '</i>'+
                                        '</a>'+

                                        '<a  href="" data-toggle="tooltip" data-placement="top" title="  " >'+ 
                                          //dislike icons 
                                        '<i id="comment-dislike" class="fas fa-thumbs-down comment-dislike">'+
                                           120
                                        '</i>'+
                                        '</a>'+

                                        '<a  class="" href="" data-toggle="tooltip" data-placement="top" title=" ">'+
                                          //like  icons
                                          '<i id="comment-like" class="fas fa-thumbs-up comment-like">'+
                                            120
                                          '</i>'+
                                        '</a>'+

                                    '</div>'+


                                    // user information
                                    '<div class="commenter-info order-1">'+
                                      '<div class=" text-muted commenter-action-time">'+
                                         "" 
                                         +json.comments[i].comment_date_updated+
                                      '</div>'+
                                      '<div class="user-avatar">'+
                                          '<img src="{% static "towns/firefly.gif" %}">'+
                                      '</div>'+
                                      '<div class="commenter-details">'+
                                        '<a id="commenter-username" class="" href="{% url "user_profile" %}"> user name </a>'+
                                        '<div class="commenter-extra-info">'+
                                           '<span>'+ 

                                           '</span>'+
                                           '<span>'+

                                           '</span>'+


                                        '</div>'+
                                      '</div>'+
                                    '</div>'+


                              '</div>'+

                        '</div>');




}

error here ate the closing parenthesis:

for(var j = 0; j < json.images.length; j++) {

and

 '</div>');

 }

You shouldn’t do that, it’s a flaw in your logic, instead of “making a nested for loop inside of a string” you should make a for loop that generates a string and append it to that string.

For example basing it on your code:

let out = "some html here";
for(var j = 0; j < json.images.length; j++) // some condition here
    out += "some more html here";
out += "some more html";
comment_box_start.append(out);

Tagged : /

Code Bug Fix: CKEDitor 4 sefocus on clicking label

Original Source Link

I have a CKEditor 4 instance:

  <label for="message_text_1_0">Kurzfassung des Beitrags</label>
<div style="float:left">


<textarea id="message_text_1_0" name="message_text_1_0">
</textarea>
</div>
<script>CKEDITOR.replace('message_text_1_0', {"customConfig": "/my/path/file.js", "Width": "600px", "External": 0, "Height": "100px", "DefaultLanguage": "de", "language": "en"});<script>

Everything works fine so far, but I want a click on the label, to pass the focus to the editor.

Unfortunately neither

$(document).on('click', 'label', 
    function () {
        let target = $(this).attr('for'); 
        if (CKEDITOR.instances[target]){ 
            CKEDITOR.focusManager(CKEDITOR.instances[target]).focus(); 
            return false; 
        }
    }
)

nor

$(document).on('click', 'label', 
    function () {
        let target = $(this).attr('for'); 
        if (CKEDITOR.instances[target]) { 
            CKEDITOR.instances[target].focus();
            return false; 
        }
    }
)

work.

Putting these into setTimeout hasn’t helped either. (JQuery is loaded and used)

Any help would be appreciated!

$(document).on('click', 'label', 
    function (ev) {
        let target = $(this).attr('for'); 
        if (CKEDITOR.instances[target]) {
            CKEDITOR.instances[target].focus(); 
            ev.preventDefault();
            return false; 
        }
    }
)

was the solution.

Tagged : / / / /